我无法找到让用户重复代码而不必退出shell的方法。这是我到目前为止所做的。
https://....
我想知道如何将所有这些代码应用于一个变量或重复,而不必编写50次。
答案 0 :(得分:2)
我建议将整个事情包含在while循环中。
start = True
while start == True:
"""your code here"""
answerAgain = raw_input("Do you want to restart this program ? ")
if answerAgain == ("Yes", "yes", "ya", "Ya", "Okay", "Sure", "Si", "Start"):
start = True
else:
start = False
如果start == True,那么整个代码将再次运行。
我还建议您使用列表作为回复。
responses = ["Super Close", "Pretty Close", "Fairly Close", "Not Really Close", "Far"]
通过这种方式,您可以使用差异映射到相应的响应:
print responses[abs(answer - randomNum) - 1]
答案 1 :(得分:0)
将代码置于while
循环中以重复它。
start = True
while start:
# code
if answerAgain.lower() in ('no', 'niet', 'bye'):
start = False
答案 2 :(得分:0)
quit()
彻底退出程序。所以也许这样:
import random
while(True):
randomNum = random.randint(1, 10)
answer = 0
while abs(answer - randomNum) > 0:
answer = int(input("Try to guess a random number between 1 and 10. "))
if abs(answer - randomNum) == 1:
print("Super Close")
elif abs(answer - randomNum) == 2:
print("Pretty Close")
# the other cases ...
# gets here if abs(answer - randonNum) == 0, i.e. they guessed right
print("Good Job!", randomNum)
answerAgain = input("Do you want to restart this program ? ")
if answerAgain.lower() in ["yes", "ya", "y", "okay", "sure", "si", "start"]:
pass
else:
print("See ya next time!")
quit()