简体   繁体   中英

UnboundLocalError: local variable 'text_in_use' referenced before assignment

I can set the variable and print it directly after if choice == 1. But if choice == 2 i cant print it out the text that was set, I get an error.

(UnboundLocalError: local variable 'text_in_use' referenced before assignment)

How can i fix this?

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

i just want it to print the text that was set.

-- Hi Linus,

Your variable

text_in_use

only is set if your first condition is met. So if your codes skips that condition and moves on to:

elif choice == 2

the variable hasn't been set yet.

Since, the function recursively calls itself after every option, you also can't add the variable before the first clause as I initially suggested.

So I'm changing my answer to the following:

At this point I would also like to add that a function without any exit may not be what you ultimately want to use. So I commented out the recursive call in option 5.

My suggestion is to use a simple 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()

You should mark text_in_use variable as global. You reference it in function from outer scope

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

   #rest of code

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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