[英]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?
I'm just starting to learn Python and I'm writing a simple dice rolling program that asks the user for the number of dice and how many sides the dice will have. 我刚开始学习Python,并且正在编写一个简单的骰子滚动程序,该程序向用户询问骰子的数量以及骰子的边数。
So far I have this: 到目前为止,我有这个:
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
It works, but it doesn't seem very efficient to me. 它可以工作,但是对我来说似乎并不是很有效。 I'm wondering if there might be a way to ask the user at the end of the first for loop if they want to play again, and, if they say yes, ask them for new values and repeat the for loop again.
我想知道是否有一种方法可以在第一个for循环结束时询问用户是否要再次播放,如果他们说是,请向他们询问新值并再次重复for循环。 Is there any way to do something like this?
有什么办法可以做这样的事情吗?
The general application is a "stay while valid" loop, such as: 通用应用程序是“有效时保持”循环,例如:
replay = True
while replay:
... remainder of code
replay = raw_input("Roll again? (y or n)") == 'y'
Note that this is a simple version, with no error checking: if the user enters a 'y', the program continues; 注意,这是一个简单的版本,没有错误检查:如果用户输入“ y”,则程序继续;否则,程序将继续。 anything else terminates the wonderful world of rolling a douse (never say 'die' :-) ).
其他任何事情都终止了滚转杜兹的绝妙世界(永远不要说'die':-))。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.