|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
今天刚看了小甲鱼的课,看到数据类型那一讲,尝试了一下
>>> a = 5.99
>>> b = int(a)
>>> print(b)
5
在IDLE中,直接输入没有问题
然后我新建了一个
a = input('请输入一个数字:')
b = int(a)
print(b)
请输入一个数字:5.99
Traceback (most recent call last):
File "E:/1.py", line 2, in <module>
b = int(a)
ValueError: invalid literal for int() with base 10: '5.99'
>>>
输入数字为整数的话,没有问题,想知道,为什么输入小数,会报错。
萌新一枚,谢谢各位大佬的帮助。
class int(x, base=10)
Return an integer object constructed from a number or string x, or return 0 if no arguments are given. If x is a number, return x.__int__(). For floating point numbers, this truncates towards zero.
If x is not a number or if base is given, then x must be a string, bytes, or bytearray instance representing an integer literal in radix base. Optionally, the literal can be preceded by + or - (with no space in between) and surrounded by whitespace. A base-n literal consists of the digits 0 to n-1, with a to z (or A to Z) having values 10 to 35. The default base is 10. The allowed values are 0 and 2-36. Base-2, -8, and -16 literals can be optionally prefixed with 0b/0B, 0o/0O, or 0x/0X, as with integer literals in code. Base 0 means to interpret exactly as a code literal, so that the actual base is 2, 8, 10, or 16, and so that int('010', 0) is not legal, while int('010') is, as well as int('010', 8).
看说明文档,红字处说明了,如果输入不是数字类型的,那么那个变量代表的必须是一个整数
对于你所举的例子,
第一个 a = 5.99 a是数字类型(浮点型),所以那么转换没有问题
第二个 a = input('请输入一个数字:') 这个得到的是个字符类型,但这个字符又不是代表整数的字符,所以就会报错了
|
|