1. 隐式类型转换
某些情况下 , Python 会自动将一个类型转为另外一个类型。例如 , 在进行整数和浮点数运算时 , Python 会自动将整数转为浮点数。同时 , 两个整数相除时也会自动转为浮点数的相除。例如:
>>> a = 25
>>> b = 3.14
>>> c = a+b
>>> print("datatype of a:",type(a))
datatype of a: <class 'int'>
>>> print("datatype of b:",type(b))
datatype of b: <class 'float'>
>>> print("Value of c:",c)
Value of c: 28.14
>>> print("datatype of c:",type(c))
datatype of c: <class 'float'>
>>> print(a/3)
8.333333333333334但是 , 如果一个数(整数、浮点数等)和一个字符串想加 , 就不会进行"隐式类型转换"。例如:
>>> print(30+"world")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for +: 'int' and 'str'
>>>这时需要使用 Python 的内置函数进行“显式类型转换”。
2. 显示类型转换
内置函数 str()将数值类型(int、float、complex)的值转为字符串 str 类型。例如:
>>> print(3*str(30)+"world")
303030world
>>> print(3*str(3.14))
3.143.143.14
>>> print( 3*str(3+6j) )
(3+6j)(3+6j)(3+6j)内置函数 int()既可将一个合适格式的字符串类型的值转为 int 类型的值,也可以将一个 float 类 型的值转为 int 类型的值(此时,该值小数点后的部分会被截断)。例如:
>>> a = int(3.14)
>>> print(type(a))
<class 'int'>
>>> print(a)
3
>>> a = int('1000')
>>> print(type(a))
<class 'int'>
>>> print(a)
1000但是,内置函数 int()不能将一个不合适格式的字符串转为 int 类型的值。
>>> a = int('1,000')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: '1,000'
>>>产生“无效的 int 文字量”的 ValueError(值错误)
内置函数 float()既可将一个合适格式的字符串类型的值转为 float 类型的值,也可将一个 int 类 型的值转为 float 类型的值。例如:
>>> print(30+float('3.14'))
33.14
>>> print(float(314))
314.03. 输入
可以通过内置函数 input()从键盘输入数据 , 其语法格式为:
input(prompt='')其中 , prompt 是一个用于提示信息的字符串。例如 :
name = input("请输入你的用户名: ")
print(name)执行上述代码, 输出结果如下:
请输入你的用户名: 小白
小白再如:
number = input("请输入一个数: ")
print(type(number))
print(number+30)第一个函数 print()打印 number 的类型,第二个函数 print()因 int 和 str 相加而产生 TypeError(语法错误)。输出结果如下:
请输入一个数: 34
<class 'str'>
----------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-6-9fef67d3d02c> in <module>()
1 number = input("请输入一个数: ")
2 print(type(number))
----> 3 print(number+30)
TypeError: must be str, not int在执行 number+30 时出现了类型错误。函数 input()输入的永远是一个字符串,所以让输入的字 符串 34 和 int 类型的值 30 相加是非法的。正确的方法是将输入的代表数值的字符串用 int()或float() 函数转化为数值类型,再和int 类型的值相加。
number = input("请输入一个数: ")
print(float(number)+30)执行:
请输入一个数: 34
64.0