简体   繁体   English

Python:while(True!= True)循环

[英]Python: while (True != True) loop

I started learning to code this week so I'm playing around with small programs that I'm creating to try to get a better understanding of how it work. 我从本周开始学习编码,因此我正在研究自己创建的小程序,以期更好地了解它的工作方式。

One of the programs I made is a Pig Latin translator that loops until the user exits. 我制作的程序之一是Pig拉丁语翻译程序,该程序一直循环播放直到用户退出。 The program works but the logic isn't making any sense to me. 该程序可以工作,但是逻辑对我来说没有任何意义。

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()

My question is, why does this program work? 我的问题是,为什么该程序有效? I set run to False and I set the loop to run as long as run != True. 我将run设置为False,并将循环设置为只要run!= True即可运行。 No problem there, however when I defined cont(), I set run to take on the value True if the user inputs "y". 没问题,但是当我定义cont()时,如果用户输入“ y”,我会将run设置为取值为True。 True != True should be False (if I understand correctly) and the loop should end, but instead it is working as I wanted it to. True!= True应该为False(如果我理解正确的话),并且循环应该结束,但是它正在按我的意愿工作。

Is this a coding mistake that I've made or am I just thinking about this the wrong way? 这是我犯的编码错误,还是我只是在以错误的方式考虑? Thank you in advance. 先感谢您。

Edit: Thank you very much to everyone that answered. 编辑:非常感谢所有回答的人。 I hadn't learned about local and global variables yet. 我还没有了解局部和全局变量。

The run inside the cont function is a local variable. run里面cont函数是一个局部变量。 Changing its value has no effect on the global variable that the while loop refers to. 更改其值不会影响while循环所引用的全局变量。

To expand on what others have already stated, run on these lines 为了扩展其他人已经说过的内容,请在这些行上run

if loop == "y" :
    run = True
elif loop == "n" :
    run = False

are not referring to the same run defined by 所指的不是相同的run

#Can be set to True if while (run != True) is set to while (run == True).
run = False

run in the cont function is a local variable to your function, not the globaly defined run . cont函数中run是函数的局部变量,而不是全局定义的run

There are a couple (at least) ways to fix this. 有至少两种方法可以解决此问题。 The preferred (imo) way to do it is have cont return a new value to be assigned to run . 首选的(imo)方法是让cont返回要分配给run的新值。 That would look like 看起来像

#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)

The other (less preferred) way would be to use the global run variable inside of your cont function. 另一种(不太受欢迎)的方法是在cont函数内部使用全局run变量。 This is achieved using the global keyword. 这是使用global关键字实现的。

That would look like this: 看起来像这样:

#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()

** Couple side notes **情侣配音
In my first example I return _run when the value is y and not _run when the value is n . 在我的第一个示例中,当值为y时返回_runnot _run当值为n时返回_run This allows you to change you initial run value to be True, and change the while condition without having to change the cont function itself. 这使您可以将初始run值更改为True,并更改while条件,而不必更改cont函数本身。

You don't need to actually change the run value at all if you use the global and the user enters n since you exit before the function returns. 如果您使用全局变量,并且用户输入n因为您在函数返回之前退出,则实际上根本不需要更改run值。

You might be better off changing your if conditional checks to 你可能会关闭改变你的更好if有条件的检查

if loop in ("yes", "y"):
if loop in ("no", "n"):

since lots of people don't read full instructions :) 因为很多人没有阅读完整的说明:)

I think this is probably because of the scope of your run variable; 我认为这可能是因为您的运行变量的范围; because you're not returning run from your cont function. 因为您没有从续函数返回运行。 I believe what your != True check sees is always going to be False outside of that function, though obviously you can successfully end the program within the function. 我相信您的!= True检查所看到的在该函数之外始终会为False,尽管您显然可以在该函数内成功结束该程序。

The problem is that the run variable defined in cont() is not the same as the run variable defined in the global scope. 的问题是,在run中定义的变量cont()是不一样的run在全球范围内定义的变量。 (If you aren't sure what I mean by that you might want to look at https://docs.python.org/3.4/tutorial/classes.html#python-scopes-and-namespaces . Perhaps a better approach for your code would be to have cont() return True or False . It is also more intuitive and readable to use True for when you want to continue. Here's how I would rewrite it. (如果不确定我的意思,则可能需要查看https://docs.python.org/3.4/tutorial/classes.html#python-scopes-and-namespaces 。也许是一种更好的方法,代码将让cont()返回TrueFalse ,当您想继续时使用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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM