【问题标题】:Python: while (True != True) loopPython:while(真!=真)循环
【发布时间】: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 (如果我理解正确的话)并且循环应该结束,但它正在按我想要的方式工作。

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

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

【问题讨论】:

    标签: python loops


    【解决方案1】:

    为了扩展其他人已经说过的内容,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 时返回_run,当值为n 时返回not _run。这允许您将初始 run 值更改为 True,并更改 while 条件,而无需更改 cont 函数本身。

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

    您最好将if 条件检查更改为

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

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

    【讨论】:

      【解决方案2】:

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

      【讨论】:

        【解决方案3】:

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

        【讨论】:

          【解决方案4】:

          问题是cont()中定义的run变量与全局范围内定义的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()
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2021-04-09
            • 1970-01-01
            • 2021-06-03
            • 2020-08-01
            • 2021-01-01
            相关资源
            最近更新 更多