繁体   English   中英

Python:while(True!= True)循环

[英]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()

我的问题是,为什么该程序有效? 我将run设置为False,并将循环设置为只要run!= True即可运行。 没问题,但是当我定义cont()时,如果用户输入“ y”,我会将run设置为取值为True。 True!= True应该为False(如果我理解正确的话),并且循环应该结束,但是它正在按我的意愿工作。

这是我犯的编码错误,还是我只是在以错误的方式考虑? 先感谢您。

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

run里面cont函数是一个局部变量。 更改其值不会影响while循环所引用的全局变量。

为了扩展其他人已经说过的内容,请在这些行上run

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

所指的不是相同的run

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

cont函数中run是函数的局部变量,而不是全局定义的run

有至少两种方法可以解决此问题。 首选的(imo)方法是让cont返回要分配给run的新值。 看起来像

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

另一种(不太受欢迎)的方法是在cont函数内部使用全局run变量。 这是使用global关键字实现的。

看起来像这样:

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

**情侣配音
在我的第一个示例中,当值为y时返回_runnot _run当值为n时返回_run 这使您可以将初始run值更改为True,并更改while条件,而不必更改cont函数本身。

如果您使用全局变量,并且用户输入n因为您在函数返回之前退出,则实际上根本不需要更改run值。

你可能会关闭改变你的更好if有条件的检查

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

因为很多人没有阅读完整的说明:)

我认为这可能是因为您的运行变量的范围; 因为您没有从续函数返回运行。 我相信您的!= True检查所看到的在该函数之外始终会为False,尽管您显然可以在该函数内成功结束该程序。

的问题是,在run中定义的变量cont()是不一样的run在全球范围内定义的变量。 (如果不确定我的意思,则可能需要查看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