1. isinstance(变量名,类型) #判断什么类型
ps:
只支持输入两个参数,输入3个参数会报错
>>> isinstance (a,int,float)
Traceack (most recent call last):
File "", line 1, in
TypeError: isinstance expected 2 arguments, got 3
>>> isinstance (a,int)
True
>>> b=1.1234
>>> isinstance(b,float)
True
>>> c=1+1j
>>> isinstance(c,complex)
True
>>> d=[1,2,3,4]
>>> isinstance(d,list)
True
>>> e=(1,2,3,4)
>>> isinstance (e,tuple)
True
>>> f="abc"
>>> isinstance(f,str)
True
>>> g={1:4,a:b}
>>> isinstance(g,dict)
True
>>> h={1,2,3,4}
>>> type(h)
>>> isinstance (h,set)
True
>>> isinstance(False,bool)
True
>>> isinstance(False,bool)
True
>>> bool(a)
True
>>> bool(1)
True
>>> bool(-1)
True
>>> bool(1+1j)
True
>>> bool([])
False
>>> bool({})
False
>>> bool( )
False
>>> bool("")
False
>>> bool(0)
False
用途:在实现函数时,需要传入一些变量,因为python是弱语言类型,实现不需要声明变量类型就可以使用的。赋予什么值,就默认为什么类型。所以在给函数传参的时候,事先要判断一下是什么类型。如果类型不对,就会报错儿。
>>> a=1
>>> b="2"
>>> a+b
Traceback (most recent call last):
File "", line 1, in
TypeError: unsupported operand type(s) for +: 'int' and 'str'
>>> type=1.2
>>> isinstance(type,float)
True
>>> type(1.2)
Traceback (most recent call last):
File "", line 1, in
TypeError: 'float' object is not callable
类型错误:'float'对象不可调用
原因:将关键字赋了值,在代码里重内置类型.新定义了type,如type=1.2,这时你自己调用的是代码里定义的type,而不是python
解决方法:删掉重新定义的关键字del type
2. 常用的计算:
1) 加+
>>> 1+1
2
2) 减-
>>> 1-1
0
3) 乘*
>>> 56*2
112
4) 除/
>>> 1/2
0.5
>>> 1/3
0.3333333333333333 #自动取小数,而非取整。
>>> 1/0
Traceback (most recent call last):
File "", line 1, in
ZeroDivisionError: division by zero #0不能做除数:
5) 取整//
>>> 1//2
0
>>> 9//2
4
>>> 9//10
0 #不存在四舍五入的情况,只取商。
6) 四舍五入round(数字,保留的位数)
>>> round(1.25,1) #小数点要保留的位数后面如果是5,5会更加靠近偶数。
1.2 如果5前面是偶数,那不会进位
>>> round(1.25,0)