繁体   English   中英

UnboundLocalError:分配前引用了局部变量“text_in_use”

[英]UnboundLocalError: local variable 'text_in_use' referenced before assignment

如果选择 == 1,我可以设置变量并直接打印它。但是如果选择 == 2,我无法将设置的文本打印出来,我会收到错误消息。

(UnboundLocalError:赋值前引用了局部变量'text_in_use')

我怎样才能解决这个问题?

text_in_use = ''
encrypt_key = ''

def menu():
    choice = int(input("""1: Input text to work with
2: Print the current text
3: Encrypt the current text
4: Decrypt the current text
5: Exit
Enter Choice: """))

    if choice == 1:
       text_in_use = str(input("Enter Text: ")).upper()
       print("Text to use was set to:", text_in_use)
       menu()
    elif choice == 2:
        print(text_in_use) #this is where i get the error <-----
        menu()
    elif choice == 3:
        print("3")
        menu()
    elif choice == 4:
        #decrypt()
        print("4")
        menu()
    elif choice == 5:
        #exit()
        print("5")
        menu()

menu()

我只想让它打印设置的文本。

——嗨,莱纳斯,

你的变量

text_in_use

只有在满足您的第一个条件时才设置。 因此,如果您的代码跳过该条件并继续执行以下操作:

elif choice == 2

该变量尚未设置。

由于 function 在每个选项之后递归调用自身,因此您也不能像我最初建议的那样在第一个子句之前添加变量。

所以我将我的答案更改为以下内容:

在这一点上,我还想补充一点,没有任何出口的 function 可能不是您最终想要使用的。 所以我注释掉了选项 5 中的递归调用。

我的建议是使用简单的 class:

class Menu:
  def __init__(self):
    self.text_in_use = ''
    self.encrypt_key = ''

    self.build_menu()

  def build_menu(self):

    choice = int(input(
      """
      1: Input text to work with
      2: Print the current text
      3: Encrypt the current text
      4: Decrypt the current text
      5: Exit

      Enter Choice: 
      """
    ))

    if choice == 1:
      self.text_in_use = str(input("Enter Text: ")).upper()
      print("Text to use was set to:", self.text_in_use)
      self.build_menu()
    elif choice == 2:
      print(self.text_in_use)
      self.build_menu()
    elif choice == 3:
      print("3")
      self.build_menu()
    elif choice == 4:
      #decrypt()
      print("4")
      self.build_menu()
    elif choice == 5:
      #exit()
      print("5")
      # self.build_menu() do not call this again so it actually exits.

Menu()

您应该将 text_in_use 变量标记为全局变量。 您从外部 scope 在 function 中引用它

def menu():
    global text_in_use
    choice = int(input("your_text"))

   #rest of code

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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