我这周开始学习代码,所以我在玩我正在创建的小程序,试图更好地理解它是如何工作的。在
我做的一个程序是一个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 as run!=正确。没有问题,但是当我定义cont()时,我将run设置为在用户输入“y”时采用True值。真的!=True应该是False(如果我理解正确的话),循环应该结束,但是它正在按照我想要的方式工作。在
这是我犯的一个编码错误,还是我想错了?提前谢谢你。在
编辑:非常感谢所有回答的人。我还没学过局部和全局变量。在