我想知道如何根据用户输入制作循环?
import random
die1 = random.randrange(6) + 1
die2 = random.randrange(6) + 1
total = die1 + die2
raw_input("Ready to roll dice 1? Press enter if you are.")
print "You rolled a", die1, "with dice 1."
raw_input("Ready to roll dice 2? Press enter if you are.")
print "And a", die2, "with dice 2."
print "Giving you a total of", total
如果在给予total
之后用户想要再次滚动,我该怎么做? Ideally Press 1 to play again or press 2 to exit.
答案 0 :(得分:0)
将骰子卷放入while循环中。打印完总数后,使用raw_input让用户输入变量的值。
myVar = raw_input("Enter 'y' to roll again or anything else to quit: "
制作while循环的条件while myVar == 'y':
不要忘记将myVar设置为等于' y'在循环之前。
答案 1 :(得分:0)
你可以把整个事情放在一个while循环中。在下面的代码中,按1继续或任何键退出:
import random
replay = True
while(replay):
die1 = random.randrange(6) + 1
die2 = random.randrange(6) + 1
total = die1 + die2
raw_input("Ready to roll dice 1? Press enter if you are.")
print "You rolled a", die1, "with dice 1."
raw_input("Ready to roll dice 2? Press enter if you are.")
print "And a", die2, "with dice 2."
print "Giving you a total of", total
replay_option = raw_input("Press 1 to play again or press any key to exit")
if replay_option == '1':
replay = True
else:
replay = False