[英]Simple dice roll program issue
I have created a program where the user can select a certain sided dice then it rolls and outputs the number generated, it then asks if the user wants to roll again and by using a while loop. 我创建了一个程序,用户可以选择某个侧面的骰子,然后掷骰子并输出生成的数字,然后询问用户是否要掷骰子并使用while循环。 i have wrote the program and for some reason it keeps on repeating the input dice side number prompt and i don't know why, here is the code
我已经编写了程序,由于某种原因,它会继续重复输入骰子边号提示,但我不知道为什么,这是代码
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')
I suspect it is something to do with the while loop or the indentation, but I have been fiddling with it for like 3o mins and i cant get it to work properly, so if someone could help me out here it would be appreciated, Thanks ! 我怀疑这与while循环或缩进有关,但是我一直在摆弄它约3分钟,而我无法使其正常工作,因此,如果有人可以在这里帮助我,将不胜感激,谢谢!
The indentation on else: roll_agn=input
is such that it only runs after you exit the while
loop - but the while
loop can never end until you run the else
clause, therefore infinite loop. else: roll_agn=input
的缩进仅在退出while
循环后才运行-但是while
循环永远不会结束,直到您运行else
子句,即无限循环。
Here is a cleaned-up, better-structured version: 这是清理后的结构更好的版本:
# assumes Python 3.x
from random import randint
def get_int(prompt):
while True:
try:
return int(input(prompt)) # if Python 2.x use raw_input instead of input
except ValueError:
# not an int
pass
def get_yn(prompt):
while True:
value = input(prompt).strip().lower() # if Python 2.x use raw_input instead of input
if value in {'y', 'yes'}:
return True
elif value in {'n', 'no'}:
return False
def roll(sides):
return randint(1, sides)
def main():
while True:
sides = get_int("Number of sides on die (4, 6, or 12)? ")
if sides in {4, 6, 12}:
print("You rolled a {}".format(roll(sides)))
else:
print("U no reed gud?")
if not get_yn("Play again (y/n)? "):
print("Thanks for playing!")
break
if __name__=="__main__":
main()
It looks like you have indentation problems with the if statements. 看起来if语句存在缩进问题。 Try lining up elif with if.
尝试将ifif与elif对齐。
if dice ==4:
print(random.randint(1,4))
elif dice ==6:
print(random.randint(1,6))
elif dice ==12:
print(random.randint(1,12))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.