[英]While Loop occuring once more than intended (Python)
在if
/ elif
語句中包含的代碼將其相關變量設置為False
后,由x
變量控制的while
循環不會停止。 而不是停止while
循環,當x
變量設置為False
時,它允許循環再發生一次,然后導致循環停止。 這是什么原因造成的?
def GameIntro():
# Declaration of outer while loop variable
x = True
# Outer while loop that I want to keep running until the player enters the 'yes' branch of the if statement
while x:
# Declaration of inner while loop variable
j = True
playerName = input("Please enter your name:")
print("\nWelcome " + playerName)
print("At any time, type 'Help' to bring up the list of possible actions." + "\n")
while j:
beginGame = input(playerName + ", are you ready to begin? [Y] or [N]")
beginGame = beginGame.upper()
if beginGame == "Y" or beginGame == "YES":
# At this point I want this function to end and for it to return a True value. The # print is purely for testing purposes.
print("Yes Test")
x = False
j = False
return True
elif beginGame == "N" or beginGame == "NO":
# At this point, I want the inner loop to stop and for the outer loop to occur again. # This works.
print("No Test")
j = False
else:
print("Please enter either [Y] or [N]")
GameIntro()
這是我得到的 output。
Please enter your name:Bob
Welcome Bob
At any time, type 'Help' to bring up the list of possible actions.
Bob, are you ready to begin? [Y] or [N]
Y
Yes Test
Please enter your name:Bob2
Welcome Bob2
At any time, type 'Help' to bring up the list of possible actions.
Bob2, are you ready to begin? [Y] or [N]
Y Yes Test
Run game
Process finished with exit code 0
“運行游戲”來自另一個 function,它從if
/ elif
語句的 yes 分支接收返回的True
。
我不認為你真的需要一個單獨的變量,你可以使用beginGame
,例如作為你的標記值
我還建議在循環中的每個點都放置一個break
點,而不是依賴return
,除非您無法安全返回 state
def validInput(x):
return x in {'YES', 'Y'}
def intro():
playerName = input("Please enter your name:")
print("\nWelcome " + playerName)
print("At any time, type 'Help' to bring up the list of possible actions." + "\n")
beginGame = 'N'
while not validInput(beginGame):
beginGame = input(playerName + ", are you ready to begin? [Y] or [N]").upper()
if beginGame == "HELP":
print('[Y] or [N]?')
elif validInput(beginGame):
print('Starting Game!')
print(f'Getting {playerName} ready to play...')
return (playerName, True)
playerName, ready_intro = intro()
if ready_intro:
main_game(playerName)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.