我做了这个例子但是它没有运行try和Python中的处理错误。
def my_fun(numCats):
print('How many cats do you have?')
numCats = input()
try:
if int(numCats) >=4:
print('That is a lot of cats')
else:
print('That is not that many cats')
except ValueError:
print("Value error")
我试过了:
except Exception:
except (ZeroDivisionError,ValueError) as e:
except (ZeroDivisionError,ValueError) as error:
我做了其他的例子,它能够捕获ZeroDivisionError
我正在使用Jupyter笔记本Python 3.任何帮助在这件事非常感谢。
我在打电话
my_fun(int('six'))
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-39-657852cb9525> in <module>()
----> 1 my_fun(int('six'))
ValueError: invalid literal for int() with base 10: 'six'
一些问题:
numCats
,因为它已更改为用户提供的任何内容。my_fun()
,这意味着永远不会有任何输出,因为函数只在被调用时运行。这应该工作:
def my_fun():
print('How many cats do you have?\n')
numCats = input()
try:
if int(numCats) > 3:
print('That is a lot of cats.')
else:
print('That is not that many cats.')
except ValueError:
print("Value error")
my_fun() ## As the function is called, it will produce output now
这是您的代码的重写版本:
def my_fun():
numCats = input('How many cats do you have?\n')
try:
if int(numCats) >= 4:
return 'That is a lot of cats'
else:
return 'That is not that many cats'
except ValueError:
return 'Error: you entered a non-numeric value: {0}'.format(numCats)
my_fun()
说明
input()
将输入前显示的字符串作为参数。input()
提供输入,因此您的函数不需要参数。return
价值观,如有必要,之后再打印。而不是你的功能print
字符串和return
没有。