[英]Python: while (True != True) loop
我從本周開始學習編碼,因此我正在研究自己創建的小程序,以期更好地了解它的工作方式。
我制作的程序之一是Pig拉丁語翻譯程序,該程序一直循環播放直到用戶退出。 該程序可以工作,但是邏輯對我來說沒有任何意義。
pyg = "ay" #Pig Latin words end with ay.
def translate(): #Creating a function.
original = input("Enter a word: ").lower() #Ask for input then convert to lower.
if len(original) > 0 and original.isalpha() : #isalpha() verifies only abc's and more than one letter.
first = original[0] #Assigns the first letter of the string to first.
latin = original[1:] + first + pyg #Adds original starting at 2nd letter with first and pyg.
print(latin)
else:
print("You did not enter a valid word, please try again.")
translate() #If you did not enter valid word, then call function again until you do.
translate() #Don't forget to actually call the function after you define it.
#Set run to False.
#Can be set to True if while (run != True) is set to while (run == True).
run = False
#Defining cont(). Ask for imput and error handling.
def cont():
loop = input("Would you like to convert another word? (y/n): ").lower()
if loop == "y" :
run = True
elif loop == "n" :
run = False
print("Thank you for using this program, have a nice day!")
exit()
else :
print("You did not enter a valid response, please try again.")
cont()
cont()
#Infinite loop as long as run is not equal to True.
while (run != True) :
translate()
cont()
我的問題是,為什么該程序有效? 我將run設置為False,並將循環設置為只要run!= True即可運行。 沒問題,但是當我定義cont()時,如果用戶輸入“ y”,我會將run設置為取值為True。 True!= True應該為False(如果我理解正確的話),並且循環應該結束,但是它正在按我的意願工作。
這是我犯的編碼錯誤,還是我只是在以錯誤的方式考慮? 先感謝您。
編輯:非常感謝所有回答的人。 我還沒有了解局部和全局變量。
在run
里面cont
函數是一個局部變量。 更改其值不會影響while循環所引用的全局變量。
為了擴展其他人已經說過的內容,請在這些行上run
if loop == "y" :
run = True
elif loop == "n" :
run = False
所指的不是相同的run
#Can be set to True if while (run != True) is set to while (run == True).
run = False
在cont
函數中run
是函數的局部變量,而不是全局定義的run
。
有至少兩種方法可以解決此問題。 首選的(imo)方法是讓cont
返回要分配給run
的新值。 看起來像
#Defining cont(). Ask for imput and error handling.
def cont(_run):
loop = input("Would you like to convert another word? (y/n): ").lower()
if loop == "y" :
return _run
elif loop == "n" :
return not _run
else :
print("You did not enter a valid response, please try again.")
return cont(_run)
...
#Infinite loop as long as run is not equal to True.
while (run != True) :
translate()
run = cont(run)
另一種(不太受歡迎)的方法是在cont
函數內部使用全局run
變量。 這是使用global
關鍵字實現的。
看起來像這樣:
#Defining cont(). Ask for imput and error handling.
def cont():
global run
loop = input("Would you like to convert another word? (y/n): ").lower()
if loop == "y" :
run = True
elif loop == "n" :
run = False
print("Thank you for using this program, have a nice day!")
exit()
else :
print("You did not enter a valid response, please try again.")
cont()
**情侶配音
在我的第一個示例中,當值為y
時返回_run
, not _run
當值為n
時返回_run
。 這使您可以將初始run
值更改為True,並更改while
條件,而不必更改cont
函數本身。
如果您使用全局變量,並且用戶輸入n
因為您在函數返回之前退出,則實際上根本不需要更改run
值。
你可能會關閉改變你的更好if
有條件的檢查
if loop in ("yes", "y"):
if loop in ("no", "n"):
因為很多人沒有閱讀完整的說明:)
我認為這可能是因為您的運行變量的范圍; 因為您沒有從續函數返回運行。 我相信您的!= True檢查所看到的在該函數之外始終會為False,盡管您顯然可以在該函數內成功結束該程序。
的問題是,在run
中定義的變量cont()
是不一樣的run
在全球范圍內定義的變量。 (如果不確定我的意思,則可能需要查看https://docs.python.org/3.4/tutorial/classes.html#python-scopes-and-namespaces 。也許是一種更好的方法,代碼將讓cont()
返回True
或False
,當您想繼續時使用True
也是更直觀和易讀的,這就是我重寫它的方式。
pyg = "ay" #Pig Latin words end with ay.
def translate(): #Creating a function.
original = input("Enter a word: ").lower() #Ask for input then convert to lower.
if len(original) > 0 and original.isalpha() : #isalpha() verifies only abc's and more than one letter.
first = original[0] #Assigns the first letter of the string to first.
latin = original[1:] + first + pyg #Adds original starting at 2nd letter with first and pyg.
print(latin)
else:
print("You did not enter a valid word, please try again.")
translate() #If you did not enter valid word, then call function again until you do.
#Defining cont(). Ask for imput and error handling.
def cont():
while True:
loop = input("Would you like to convert another word? (y/n): ").lower()
if loop == "y":
return True
elif loop == "n":
print("Thank you for using this program, have a nice day!")
return False
else :
print("You did not enter a valid response, please try again.")
translate()
while cont():
translate()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.