[英]Unbound Local Error: local variable referenced before assignment inside of a try and except statement
我試圖使用所有pythonic工具(嘗試和除語句,循環,if語句)創建一個非常簡單的菜單系統,但遇到了一些麻煩。
這是我目前的代碼和錯誤消息
def Menu():
while True:
print("""
Hello, please enter a number 1 - 4
1 - Compliment
2 - Fact
3 - Insult
4 - Quit
""")
try:
UserInput_INT = int(input("> "))
except ValueError:
UserInput_STR = (UserInput_INT)
if len(UserInput_STR) == 0:
print("You have entered nothing. Please enter a number between 1 and 4")
print("You entered a character. Please enter a number between 1 and 4")
Menu()
if UserInput_INT not in range (1, 5):
print("Invalid input please enter a whole number between 1 and 4")
continue
UserInput_STR = (str(UserInput_INT))
if UserInput_STR == '1':
print(" You look horrible today!")
elif UserInput_STR == '2':
print("Sam Birkenshaw & Jordan Ives can code better than Mr Bath. ")
elif UserInput_STR == '3':
print("You are bad at coding ")
elif UserInput_STR == '4':
quit()
菜單()
錯誤信息:
“跟蹤(最近一次通話最近):文件“ E:/ All /學校/計算機科學/代碼/ SAM損壞的code.py”,菜單UserInput_INT = int(input(“>”)))第12行,ValueError:無效以10為底的int()的文字:''
在處理上述異常期間,發生了另一個異常:
追溯(最近一次通話):文件“ E:/ All /學校/計算機科學/代碼/ SAM損壞的code.py”,第39行,位於Menu()文件“ E:/ All /學校/計算機科學/ “代碼/ SAM損壞的code.py”,菜單UserInput_STR =(UserInput_INT)中的第16行,UnboundLocalError:分配前引用了本地變量“ UserInput_INT”
我需要它,以便如果用戶不輸入任何內容,則顯示的消息不同於他們輸入字母以及輸入的字符不是接受的答案之一。
(我目前正在運行python 3.6.2)
作為輸入傳遞給程序的值不是有效的整數。 現在,當引發異常時,未分配變量UserInput_INT
導致第二個錯誤。 嘗試在轉換前將值檢查是否為整數。
input = input("> ")
UserInput_INT = int(input) if input.isdigit() else input
作為旁注,請嘗試遵循命名約定。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.