【发布时间】:2015-08-14 20:53:01
【问题描述】:
我这周开始学习编码,所以我正在玩一些我正在创建的小程序,以便更好地了解它的工作原理。
我制作的一个程序是一个 Pig Latin 翻译器,它会一直循环直到用户退出。该程序有效,但逻辑对我来说没有任何意义。
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 (如果我理解正确的话)并且循环应该结束,但它正在按我想要的方式工作。
这是我犯的编码错误,还是我只是想错了?提前谢谢你。
编辑:非常感谢所有回答的人。我还没有了解局部变量和全局变量。
【问题讨论】: