抱歉,我只是python的初学者,所以这可能是一个非常简单的问题,但我有一个代码,我想循环它,所以在代码询问用户是否要再次播放和用户输入'是'重新启动代码,'否'结束代码。如果他们输入“是”或“否”以外的任何内容,则应要求告诉他们输入“是”或“否”,然后再次提出问题。我该怎么做呢? (我确实知道while和for循环,但我不确定如何以这种方式使用它们)
答案 0 :(得分:2)
我会按以下方式进行:
while True:
# your code
cont = raw_input("Another one? yes/no > ")
while cont.lower() not in ("yes","no"):
cont = raw_input("Another one? yes/no > ")
if cont == "no":
break
如果您使用Python3,请将raw_input
更改为input
。
答案 1 :(得分:1)
这很简单:
while True:
a = input("Enter yes/no to continue")
if a=="yes":
gameplay()
continue
elif a=="no":
break
else:
print("Enter either yes/no")
游戏功能包含要执行的代码
答案 2 :(得分:1)
我的方法:
# Sets to simplify if/else in determining correct answers.
yesChoice = ['yes', 'y']
noChoice = ['no', 'n']
# Prompt the user with a message and get their input.
# Convert their input to lowercase.
input = raw_input("Would you like to play again? (y/N) ").lower()
# Check if our answer is in one of two sets.
if input in yesChoice:
# call method
elif input in noChoice:
# exit game
exit 0
else:
print "Invalid input.\nExiting."
exit 1
答案 3 :(得分:1)
我认为这就是你要找的东西
def playGame():
# your code to play
if __name__ == '__main__':
play_again = 'start_string'
while not play_again in ['yes', 'no']:
play_again = raw_input('Play Again? (type yes or no) ')
if play_again == 'yes':
playGame()
答案 4 :(得分:1)
我尝试了这个简短的布尔脚本,该脚本将保持循环,直到满足if语句为止:
something = False
while not something:
inout = raw_input('type "Hello" to break the loop: ')
if inout == 'Hello':
something = True