[英]Python if statement not working inside function
我正在嘗試猜測python中的數字游戲。 但是,在again()函數中,我似乎無法運行if語句。
當我不使用Again函數並將所有代碼復制並粘貼到相應位置時,它可以正常工作。 但是,當我使用Again函數時,“是否再次播放?” 詢問問題,但if語句被忽略,導致while循環不斷地繼續。 我嘗試使用全局函數,但是第二次輸入一個猜測,它帶有TypeError:'str'對象不可調用。
import random
def guess():
global num
num = random.randint(1,3)
guessat = input("Out of 1 to 3, which number do you guess? ")
return(guessat)
def again():
global again
again = input("Play again? ")
if again in ["y","yes"]:
guessing = True
else:
guessing = False
print("Welcome to Guess the Number!")
guessing = True
while guessing:
guessy = guess()
guessy = int(guessy)
if guessy == num:
print("You got it right!")
again()
elif guessy != num:
print("Wrong number!")
again()
quit()
當我為問題“再次播放?”輸入“否”或其他任何內容時 我希望程序退出while循環並退出。
if / else語句可以完美運行,問題出在其他地方。 更具體地說,您的代碼中有兩處錯誤。
如果變量和函數again
使用相同的名稱,則應使用不同的名稱。
guessing
變量也應該是全局變量,否則while循環將永遠不會看到它的變化。
嘗試這個:
def again():
global guessing
_again = input("Play again? ")
if _again in ["y","yes"]:
guessing = True
else:
guessing = False
還有一件事。 正如其他人已經指出的那樣,使用全局變量通常不是一個好主意,最好是讓您的函數返回某些內容。
避免在again
調用的函數中again
命名變量。 但是,對於您的無限循環問題,您可以在again
函數內設置局部變量guessing
,而無需全局變量guessing
,因此檢查while循環條件的變量完全不受影響。 我可能建議:
def again():
global guessing
play_again_input = input("Play again? ")
if play_again_input in ["y","yes"]:
guessing = True
else:
guessing = False
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.