我是python的新手,我正在练习,所以我正在做一个求和函数,现在我想输入一个不是我用try/excpet
尝试过的数字时显示一条消息错误,虽然可以,但是有时它没有,这是我现在拥有的代码:
def sum(num_1, num_2):
sum_total = num_1 + num_2
print('The answer is:',sum_total)
return sum_total
def app_sum():
try:
inp_1 = int(input('Number 1?: '))
except ValueError:
print('Invalid input, try again')
app_sum()
try:
inp_2 = int(input('Number 2?: '))
except ValueError:
print('Invalid input, try again')
app_sum()
sum(inp_1,inp_2)
app_sum()
这是我的输出:
Number 1?: 1
Number 2?: 2
The answer is: 3
Number 1?: A
Invalid input, try again
Number 1?: 1
Number 2?: A
Invalid input, try again
Number 1?: 1
Number 2?: 1
The answer is: 2
Traceback (most recent call last):
File "suma.py", line 9, in app_sum
inp_1 = int(input('Number 1?: '))
ValueError: invalid literal for int() with base 10: 'A'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "suma.py", line 24, in <module>
app_sum()
File "suma.py", line 12, in app_sum
app_sum()
File "suma.py", line 20, in app_sum
sum(inp_1,inp_2)
UnboundLocalError: local variable 'inp_2' referenced before assignment
答案 0 :(得分:2)
出现此错误的原因是,在某种情况下,您可能会将其放到程序末尾,
sum(inp_1,inp_2)
实际上没有定义inp_1或inp_2。这是因为当您单击“ except”时,您将再次运行该程序。这不会“杀死”失败的程序,而只是启动它的另一个实例。当该实例完成时,第一个实例也要结束,但是就像我们前面提到的,它有一个丢失的变量,因此引发了错误。参见Stacks;
考虑一个在食堂中相互堆叠的盘子的例子。顶部的板是第一个要卸下的板,即,放置在最底部的板在堆栈中保留的时间最长……
尽管最后一个“盘子”在堆垛中的停留时间最长,但仍需要脱掉。在我们的例子中,“最后一盘”是app_sum()的实例,该实例的输入错误。当它脱离堆栈时,会给您错误,包括在帖子中。
尝试以下方法:
def sum(num_1, num_2):
sum_total = num_1 + num_2
print('The answer is:',sum_total)
return sum_total
def app_sum():
while True:
try:
inp_1 = int(input('Number 1?: '))
inp_2 = int(input('Number 2?: '))
break
except ValueError:
print('Invalid input, try again')
sum(inp_1, inp_2)
app_sum()
输出看起来像这样:
root@alarmux:/home/abdmin/python# ./test.py
Number 1?: 1
Number 2?: 2
The answer is: 3
root@alarmux:/home/abdmin/python# ./test.py
Number 1?: a
Invalid input, try again
Number 1?: 2
Number 2?: 3
The answer is: 5
答案 1 :(得分:1)
代替递归,您可以重复执行直到给出有效答案为止。
def sum(num_1, num_2):
sum_total = num_1 + num_2
print('The answer is:',sum_total)
return sum_total
def app_sum():
inp_1 = None
while inp_1 is None:
try:
inp_1 = int(input('Number 1?: '))
except ValueError:
print('Invalid input, try again')
inp_2 = None
while inp_2 is None:
try:
inp_2 = int(input('Number 2?: '))
except ValueError:
print('Invalid input, try again')
sum(inp_1,inp_2)
app_sum()
示例输出:
Number 1?: fjksdfsdflkj
Invalid input, try again
Number 1?: 3
Number 2?: fds
Invalid input, try again
Number 2?: 4
The answer is: 7