Python基本类型,, Python是一
Python基本类型,, Python是一
Python是一门动态语言,解释执行,所有错误都是运行时产生的,即使有错误和异常,只要没有被执行到也不会有错,比如调用不存在的方法;类型是隐式的,也即无需变量类型声明;类型是动态,运行时根据变量指向的内容来决定类型,但是Python是强类型语言,即每个变量都是有类型的。 Python 基本built-in类型主要有numerics,sequences, mapping, files, classes, instances, exceptions,类型上都会存在的操作有比较、是否为真、转换为字符串toString,Python中使用str/repr(object)可转换为字符串, print(object)时会隐式调用str()。numerics: 整形 int,用c语言中的long实现, 取值范围-sys.maxint-1~sys.maxin, 无sys.minint 长整形 long, 带有L/l的integer或超出integer范围的,print时会带后缀L,无精度限制,无限大,因此Python中都是有符号数,没有unsigned类型 浮点型 float,用c中的double实现,sys.float_info, 因此Python中无单双精度区分 复数 complex, z.real, z.imag
Operation | Result | Notes |
---|---|---|
x+y | sum ofxandy | |
x-y | difference ofxandy | |
x*y | product ofxandy | |
x/y | quotient ofxandy | (1) |
x//y | (floored) quotient ofxandy | (4)(5) |
x%y | remainder ofx/y | (4) |
-x | xnegated | |
+x | xunchanged | |
abs(x) | absolute value or magnitude ofx | (3) |
int(x) | xconverted to integer | (2) |
long(x) | xconverted to long integer | (2) |
float(x) | xconverted to floating point | (6) |
complex(re,im) | a complex number with real partre, imaginary partim.imdefaults to zero. | |
c.conjugate() | conjugate of the complex numberc. (Identity on real numbers) | |
divmod(x,y) | the pair(x//y,x%y) | (3)(4) |
pow(x,y) | xto the powery | (3)(7) |
x**y | xto the powery | (7) |
Operation | Result | Notes |
---|---|---|
math.trunc(x) | xtruncated to Integral | |
round(x[,n]) | xrounded to n digits, rounding ties away from zero. If n is omitted, it defaults to 0. | 四舍五入 |
math.floor(x) | the greatest integral float <=x | |
math.ceil(x) | the least integral float >=x |
bool布尔:用于if/while后做条件判断 True:非False即为True False: None, False, 数字类型0,空容器,包括空字符串‘’, class的__nonzero__() 或__len__返回0或False的实例 bool运算符:or and not, 遵循类似java/c的short-circuit, not比non-Boolean operator优先级低,not a==b 等价于not (a==b)
比较运算符: 也用于所有类型的比较,优先级比Boolean operator高,且支持x<y<z这样的写法,x<y<z 等价x<y and y < z 且前者y仅计算一次,都遵循短路原则;不同类型的对象比较结果都是False,除非是不同类型数字或字符串比较,比如0==0L, ‘abc’==u‘abc‘返回True
Operation | Meaning | Notes |
---|---|---|
< | strictly less than | |
<= | less than or equal | |
> | strictly greater than | |
>= | greater than or equal | |
== | equal | |
!= 或 <> | not equal | (1) |
is | object identity | |
isnot | negated object identity |
bitwise operation: 位运算只对整数操作有意义,位运算优先级比数字运算符低,但比比较运算符高; ~与其他的一元运算符优先级(+,-)相同,以下表格中优先级从低到高, 负数移位会抛出ValueError异常
Operation | Result | Notes |
---|---|---|
x|y | bitwiseorofxandy | |
x^y | bitwiseexclusive orofxandy | |
x&y | bitwiseandofxandy | |
x<<n | xshifted left bynbits | (1)(2) |
x>>n | xshifted right bynbits | (1)(3) |
~x | the bits ofxinverted |
Python中很容易获取帮助: help(object):显示帮助信息 dir(object) :显示所有方法 object.__doc__ :显示文档
Python基本类型
评论关闭