我是 python 新手,我正在练习,所以我正在做一个 sum 函数,现在我想在输入不是我尝试过的数字的东西时显示一条消息错误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
慕田峪7331174
慕村9548890
相关分类