我对编码很新,并且已经分配了一个类项目,在这个项目中制作一个游戏我试图编写一个函数,在失去/死亡时
def playAgain():
函数会询问用户是否要再次播放。
from sys import exit
def playAgain():
print('Do you want to play again? (yes or no)')
while True:
if input("> ").lower().startswith('yes')== True:
start()
elif input("> ").lower().startswith('no')== True:
print ('Bye for now')
exit(0)
else:
print ("I don't understand what you mean?")
此功能'应该'询问用户是否想再次播放,并且根据输入是或否,它将转到函数start()
或退出。
问题在于,当输入第一次输入时,代码中似乎被忽略,必须第二次输入,以便在代码中发生任何事情。
这让我感到困惑,因此我们将非常感谢您对如何解决此问题的任何意见。
旁注 - 首次输入yes时似乎不会发生此问题,这意味着这可能是elif
或else
语句的问题
答案 0 :(得分:1)
from sys import exit
def playAgain():
print('Do you want to play again? (yes or no)')
while True:
choice = input("> ")
if choice.lower().startswith('yes'):
start()
elif choice.lower().startswith('no'):
print ('Bye for now')
exit(0)
else:
print ("I don't understand what you mean?")
答案 1 :(得分:0)
如果你想把它写成一个函数,那么你真的应该返回一个值作为下一步的基础。
def playAgain():
while True:
ans = input("Do you want to play again? (yes or no) ")
if ans.lower().startswith('y'):
return True
elif ans.lower().startswith('n'):
return False
else:
print ("I don't understand what you mean?")
def start():
print ("game restarted")
if playAgain():
start()
else:
print ("Bye for now")
quit()
请注意,startswith
只允许您检查y
和n
,而不是完整的字词是和否
答案 2 :(得分:0)
解决方案是为输入分配一个变量,并根据需要多次比较变量。
from sys import exit
def playAgain():
print('Do you want to play again? (yes or no)')
while True:
inp = input("> ").lower()
if inp.startswith('y'):
start()
elif inp.startswith('n'):
print ('Bye for now')
exit(0)
else:
print ("I don't understand, what do you mean?")