您好我已经完成了这个随机骰子游戏,需要帮助创建一个循环,让我在用户输入无效数字时,我希望他们再试一次。这是我的代码,请帮助!
import random
dice = int(input("What sided dice do you want to use? (e.g. 4, 6 or 12): "))
if dice == 4:
random_number = int(random.randrange(1,4))
print ("You selected a 4 sided dice")
print ("Your dice has rolled ")
print (random_number)
elif dice == 6:
random_number2 = int(random.randrange(1,6))
print ("You selected a 6 sided dice")
print("Your dice has rolled ")
print (random_number2)
elif dice == 12:
random_number3 = int(random.randrange(1,12))
print ("You selected a 12 sided dice")
print("Your dice has rolled ")
print (random_number3)
else:
print(("You didn't select a valid sided dice, try again!"))*
答案 0 :(得分:3)
你需要两件事:
while
循环,一直到你想要的东西为止;和例如,一个简单的解决方案是用当前的input
语句包装:
dice = 0
while dice not in (4, 6, 12):
dice = ...
# continue
答案 1 :(得分:1)
使用while
循环:
import random
dice = None
while dice not in (4, 6, 12):
dice = int(input("What sided dice do you want to use? (e.g. 4, 6 or 12): ")
if dice == 4:
random_number = int(random.randrange(1,4))
print ("You selected a 4 sided dice")
print ("Your dice has rolled ")
print (random_number)
elif dice == 6:
random_number2 = int(random.randrange(1,6))
print ("You selected a 6 sided dice")
print("Your dice has rolled ")
print (random_number2)
elif dice == 12:
random_number3 = int(random.randrange(1,12))
print ("You selected a 12 sided dice")
print("Your dice has rolled ")
print (random_number3)