1、什么是Python值错误?
Python ValueError 是当函数收到正确类型的参数,但不适当的值时提出的。
二、错误的例子
您将使用数学操作获得 ValueError,例如负数的平方根。
1>>> import math
2>>>
3>>> math.sqrt(-10)
4Traceback (most recent call last):
5 File "<stdin>", line 1, in <module>
6ValueError: math domain error
7>>>
3、处理价值错误的例外
以下是使用 try-except 块处理 ValueError 例外的一个简单示例。
1import math
2
3x = int(input('Please enter a positive number:\n'))
4
5try:
6 print(f'Square Root of {x} is {math.sqrt(x)}')
7except ValueError as ve:
8 print(f'You entered {x}, which is not a positive number.')
以下是与不同类型的输入程序的输出。
1Please enter a positive number:
216
3Square Root of 16 is 4.0
4
5Please enter a positive number:
6-10
7You entered -10, which is not a positive number.
8
9Please enter a positive number:
10abc
11Traceback (most recent call last):
12 File "/Users/pankaj/Documents/PycharmProjects/hello-world/journaldev/errors/valueerror_examples.py", line 11, in <module>
13 x = int(input('Please enter a positive number:\n'))
14ValueError: invalid literal for int() with base 10: 'abc'
我们的程序可以在 int() 和 math.sqrt() 函数中提取 ValueError. 因此,我们可以创建一个嵌入式试用除区块来处理两者。
1import math
2
3try:
4 x = int(input('Please enter a positive number:\n'))
5 try:
6 print(f'Square Root of {x} is {math.sqrt(x)}')
7 except ValueError as ve:
8 print(f'You entered {x}, which is not a positive number.')
9except ValueError as ve:
10 print('You are supposed to enter positive number.')
4、在函数中增加值错误
下面是一个简单的例子,我们正在为正确类型但不适当值的输入参数提取 ValueError。
1import math
2
3def num_stats(x):
4 if x is not int:
5 raise TypeError('Work with Numbers Only')
6 if x < 0:
7 raise ValueError('Work with Positive Numbers Only')
8
9 print(f'{x} square is {x * x}')
10 print(f'{x} square root is {math.sqrt(x)}')