Python UnboundLocalError:局部变量';正在使用的文本';分配前参考

Python UnboundLocalError:局部变量';正在使用的文本';分配前参考,python,python-3.x,variables,Python,Python 3.x,Variables,我可以设置变量,并在选择=1后直接打印它。但是如果choice==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 t

我可以设置变量,并在选择=1后直接打印它。但是如果choice==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\u in\u use=''
加密密钥=“”
def菜单():
choice=int(输入(““”1:输入要使用的文本
2:打印当前文本
3:加密当前文本
4:解密当前文本
5:退出
输入选项:“”)
如果选项==1:
text_in_use=str(输入(“输入文本:”).upper()
打印(“要使用的文本设置为:”,文本正在使用)
菜单()
elif选项==2:
打印(使用中的文本)#这就是我得到错误的地方——嗨,Linus

你的变量

text_in_use
仅在满足第一个条件时设置。因此,如果您的代码跳过该条件并继续:

elif choice == 2
变量尚未设置

因为,函数在每个选项之后递归地调用自己,所以也不能像我最初建议的那样在第一个子句之前添加变量

因此我将我的答案改为:

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

我的建议是使用一个简单的类:

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

您应该将“使用变量”中的“文本”标记为“全局”。 您可以从外部范围在函数中引用它

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

   #rest of code

if
语句开始之前,将
text\u in_use=str(输入(“输入文本”)).upper()移动到
if
语句开始之前。在每次输入之后,您将再次调用
menu()
,并且
menu()
的下一次执行不记得在上一次执行中输入的文本。可能最好重新排列代码,以便所有逻辑都在同一执行中发生。问题是,只有当用户在菜单中选择选项1(first if语句)时,才能从输入中设置变量。然后,当再次加载菜单并输入时,应打印它们设置的文本2@LinusRiesle-帕尔根改变了答案以反映这一点。让我知道这是否适合你。