为了方便编程,整理一些Python的基础知识,以供随时参考。
数字
整数
整数类型:int
int(a)可以把变量a的类型转变为整型。str(a)则把a变为字符型。
可执行运算:加(+)、减(-)、乘(*)、除(/)、乘方(**)
除(/)永远返回浮点数类型,如果除法运算要得到整数结果,即忽略小数,就用“//”运算。
%:计算余数。
>>> 17 / 3 # classic division returns a float
5.666666666666667
>>>17 // 3 # floor division discards the fractional part
5
>>>17 % 3 # the % operator returns the remainder of the division
2
>>>5 * 3 + 2 # result * divisor + remainder
17
>>> 5 ** 2 # 5 squared
25
>>> 2 ** 7 # 2 to the power of 7
128
复数:使用后缀 j 或者 J 就可以表示虚数部分(例如 3+5j )。
浮点数
有小数部分的数。
浮点数类型:float
字符串
1.字符串的表达:单引号(‘…’)、双引号(“…”)
2.反斜杠 \ 用来转义,可以表示字符类型的引号、换行等。配合print语句使用,效果奇佳。
>>> 'spam eggs' # single quotes
'spam eggs'
>>> 'doesn\'t' # use \' to escape the single quote...
"doesn't"
>>> "doesn't" # ...or use double quotes instead
"doesn't"
>>> '"Yes," they said.'
'"Yes," they said.'
>>> "\"Yes,\" they said."
'"Yes," they said.'
>>> '"Isn\'t," they said.'
'"Isn\'t," they said.'
>>> '"Isn\'t," they said.'
'"Isn\'t," they said.'
>>> print('"Isn\'t," they said.')
"Isn't," they said.
>>> s = 'First line.\nSecond line.'