[英]infinite while loop issue on dice roll program
我已经为一个项目编写了此代码,但是由于仅重复第一个输入函数,我就遇到了while循环问题,这是代码,如果有人可以指出我的问题并帮助我修复我的代码,我将不胜感激,thnx
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')
仅当roll_agn在循环内变为“ yes”时,才会执行while的else块。 您永远不会在while循环内更改它,因此它将永远循环。
您的else
语句是不缩进的(在循环外部),因此永不重置其中的变量,因此while
循环所需的条件始终为True
,因此为无限循环。 您只需要缩进:
elif dice ==12:
...
else:
^ roll_agn = input()
正如其他人指出的那样,您的缩进不正确。 这里有一些关于如何进一步改善代码的建议
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')
无论玩家输入什么,这都将起作用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.