我开始学习本周的代码,所以我正在玩弄我创建的小程序,试图更好地理解它的工作原理。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()
我的问题是,为什么这个程序工作?我将运行设置为False,并将循环设置为只要运行!= True即可运行。那里没问题,但是当我定义cont()时,如果用户输入“y”,我将运行设置为True。 True!= True应该是False(如果我理解正确)并且循环应该结束,但是它会按照我的意愿工作。
这是我犯的一个编码错误还是我只是想着这个错误的方式?先谢谢你。
编辑:非常感谢大家回答。我还没有了解当地和全球的变数。