繁体   English   中英

python中是否有任何方法可以通过在循环结束时要求用户重复一段时间或for循环来进行?

[英]Is there any way in python to repeat a while or for loop by asking the user to do so at the end of the loop?

我刚开始学习Python,并且正在编写一个简单的骰子滚动程序,该程序向用户询问骰子的数量以及骰子的边数。

到目前为止,我有这个:

numberOfDice = eval(input("How many dice/die would you like to use? "))
numberOfSides = eval(input("How many sides will each die have? "))

for i in range(1,numberOfDice + 1) :
    roll = random.randint(1,numberOfSides)
    print(roll)

while True :
    replay = input("Would you like to play again?     ")
    if replay.lower() == "yes" :
        numberOfDice = eval(input("How many dice/die would you like to use?     "))
        numberOfSides = eval(input("How many sides will each die have?     "))
        for i in range(1,numberOfDice + 1) :
            roll = random.randint(1,numberOfSides)
            print(roll)
    else :
        break

它可以工作,但是对我来说似乎并不是很有效。 我想知道是否有一种方法可以在第一个for循环结束时询问用户是否要再次播放,如果他们说是,请向他们询问新值并再次重复for循环。 有什么办法可以做这样的事情吗?

通用应用程序是“有效时保持”循环,例如:

replay = True
while replay:
    ... remainder of code
    replay = raw_input("Roll again? (y or n)") == 'y'

注意,这是一个简单的版本,没有错误检查:如果用户输入“ y”,则程序继续;否则,程序将继续。 其他任何事情都终止了滚转杜兹的绝妙世界(永远不要说'die':-))。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM