簡體   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