python的while,Python:while(真的!=真)循环

我这周开始学习代码,所以我在玩我正在创建的小程序,试图更好地理解它是如何工作的。在

我做的一个程序是一个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(如果我理解正确的话),循环应该结束,但是它正在按照我想要的方式工作。在

这是我犯的一个编码错误,还是我想错了?提前谢谢你。在

编辑:非常感谢所有回答的人。我还没学过局部和全局变量。在

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值