骰子程序中的无限while循环问题
我为一个项目写了这段代码,但在使用while循环的时候遇到了问题,因为它只重复了第一次的输入函数。下面是我的代码,如果有人能指出我的问题并帮我修复代码,我会非常感激,谢谢!
import random
roll_agn='yes'
while roll_agn=='yes':
dice=input ('Please choose a 4, 6 or 12 sided dice: ')
if dice ==4:
print(random.randint(1,4))
elif dice ==6:
print(random.randint(1,6))
elif dice ==12:
print(random.randint(1,12))
else:
roll_agn=input('that is not 4, 6 or 12, would you like to choose again, please answer yes or no')
if roll_agn !='yes':
print ('ok thanks for playing')
3 个回答
0
你的 else
语句没有缩进(在循环外面),所以里面的变量从来没有被重置,这样 while
循环需要的条件总是 True
,因此就形成了一个无限循环。你只需要把它缩进一下:
elif dice ==12:
...
else:
^ roll_agn = input()
0
你的代码缩进有问题,正如其他人提到的那样。这里有一些建议,可以让你的代码更好一些。
import random
while True:
try:
dice = int(input ('Please choose a 4, 6 or 12 sided dice: ')) # this input should be an int
if dice in (4, 6, 12): # checks to see if the value of dice is in the supplied tuple
print(random.randint(1,dice))
choice = input('Roll again? Enter yes or no: ')
if choice.lower() == 'no': # use .lower() here so a match is found if the player enters No or NO
print('Thanks for playing!')
break # exits the loop
else:
print('that is not 4, 6 or 12')
except ValueError: # catches an exception if the player enters a letter instead of a number or enters nothing
print('Please enter a number')
这样做无论玩家输入什么都能正常工作。
1
在这个 while 循环的 else 块里,只有当 roll_agn 变成不是 'yes' 的时候,才会执行。但是在这个 while 循环里面,你并没有改变 roll_agn 的值,所以它会一直循环下去,永远不会停止。