错误:
local variable 'num1' referenced before assignment.
我尝试制作一个单独的函数,但是它不起作用(或者至少我无法使它起作用)。
def main():
while True:
try:
num1=int(input('.+'))
except ValueError:
print('Sorry, this progam only accepts values between 0 and 100.')
if num1 < 0:
return ('Sorry this program only accepts values between 0 and 100.')
else:
break
if num1 >= 90:
return ('Your letter grade is A')
if num1 >= 80:
return ('Your letter grade is B')
elif num1 >= 70:
return ('Your letter grade is C')
elif num1 >= 60:
return ('Your letter grade is D')
if num1 <=60:
return ('Your letter grade is F')
print(main())
答案 0 :(得分:1)
我假设这是在您输入无法转换为int的字符串时发生的。因此它进入try块,然后(不设置num1)引发异常,然后继续。稍后,您尝试访问未设置的num1。
您可以将数字设置为默认值:
while True:
try:
num1 = int(input())
except ValueError:
num1 = -1
if num < 0:
print('Please input a valid number between 0 - 100')
else:
break
这将使它每次无效输入仅警告用户一次,并不断提示直到他们输入有效数字
答案 1 :(得分:0)
如果您第一次输入无效数字,则会发生错误。在这种情况下,永远不会定义变量num1
。
要解决此问题,您可以在while循环外定义一次变量,如下所示:
num1 = -1
while True:
...
答案 2 :(得分:0)
稍微清洁了代码。
def my_func():
while True:
try:
this_input=int(input('.+'))
except ValueError:
print('Sorry, this progam only accepts values between 0 and 100.')
if this_input < 0 or this_input > 100:
return ('Sorry this program only accepts values between 0 and 100.')
else:
break
if this_input >= 90:
return ('Your letter grade is A')
elif this_input >= 80:
return ('Your letter grade is B')
elif this_input >= 70:
return ('Your letter grade is C')
elif this_input >= 60:
return ('Your letter grade is D')
elif this_input <=60:
return ('Your letter grade is F')
elif this_input > 100:
return ("Value out of bounds")
else:
return ""
print(my_func())
由于输入了除int之外的其他内容,因此出现错误。
daudnadeem:use_me_to_code_tests daudn$ python3 mail.py
.+A
Sorry, this progam only accepts values between 0 and 100.
Traceback (most recent call last):
File "mail.py", line 30, in <module>
print(my_func())
File "mail.py", line 9, in my_func
if this_input < 0 or this_input > 100:
UnboundLocalError: local variable 'this_input' referenced before assignment
daudnadeem:use_me_to_code_tests daudn$ python3 mail.py
.+100
Your letter grade is A