python instanceid_python入门(二):isinstance、内置函数、常用运算等

本文介绍了Python中的isinstance()函数,用于判断变量的类型,并展示了加减乘除、取整、四舍五入等基本运算。此外,还探讨了内置函数的使用,如max、pow、round,以及条件语句和类型转换操作。
摘要由CSDN通过智能技术生成

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)               

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值