我如何根据用户输入循环执行程序?

2024-09-30 08:16:33 发布

您现在位置:Python中文网/ 问答频道 /正文

我想知道如何根据用户输入进行循环?你知道吗

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.


Tags: to用户youinputrawrandomdicetotal
2条回答

把你的骰子掷成一个循环。打印总数后,使用原始输入让用户输入变量的值。 myVar = raw_input("Enter 'y' to roll again or anything else to quit: " 生成while循环的条件while myVar == 'y': 不要忘记在循环之前将myVar设置为'y'。你知道吗

你可以把整件事放在一个循环中。在下面的代码中,按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

相关问题 更多 >

    热门问题