1、数值和表达式
(1) 除法
l 操作的数值都为整数,则为整除,结果为整型:
>>> 1/2
0
l 操作的数值有浮点数,则结果为浮点型:
>>> 1.0 / 2.0
0.5
>>> 1/2.0
0.5
>>> 1.0/2
0.5
>>> 1/2.
0.5
l 为了显式的区分这两种除法,可以执行下面的语句:
>>> from __future__ import division
l 这样,浮点型除法使用“/”,而整除使用“//”:
>>> 1 / 2
0.5
>>> 1 // 2
0
(2) %:取余数
>>> 10 / 3
3
>>> 10 % 3
1
l %同样可以用于浮点型:
>>> 2.75 % 0.5
0.25
(3) **:乘方
>>> -3 ** 2
-9
>>> (-3) ** 2
9
(4) 大整数
l 整数的范围是:–2147483648~2147483647,这个范围外为大整数,需要后缀L
l Python会自动将超出上面范围的整数转换成大整数:
>>> 1987163987163981639186 * 198763981726391826 + 23
394976626432005567613000143784791693659L
(5) 十六进制和八进制数
>>> 0xAF
175
>>> 010
8
2、变量
l 变量由字母、数字和下划线组成,变量不能以数字开始,区分大小写
3、接收用户输入:input函数
>>> input("The meaning of life: ")
The meaning of life: 42
42
4、函数
l Python有很多內建函数可以应用于数值表达式:
>>> 2**3
8
>>> pow(2,3)
8
>>> abs(-10)
10
>>> 1/2
0
>>> round(1.0/2.0)
1.0
>>> int(32.9)
32
5、模块
l 可以使用模块来扩展Python的功能
l 使用import来导入模块,用“module.function”的形式来调用模块中的函数:
>>> import math
>>> math.floor(32.9)
32.0
l 使用“from module import function”的形式,可以不使用模块名做前缀,调用模块中的函数:
>>> from math import sqrt
>>> sqrt(9)
3.0
l 使用上面的形式有个不好的地方,那就是当不同模块有相同的函数时,后者会覆盖前者的函数(cmath是操作复数的模块):
>>> from cmath import sqrt
>>> sqrt(-1)
1j
>>> from math import sqrt
>>> sqrt(-1)
Traceback (most recent call last):
File "<interactive input>", line 1, in ?
ValueError: math domain error
l 变通方法:Python允许使用变量引用函数
>>> import cmath
>>> csqrt = cmath.sqrt
>>> csqrt(-1)
1j
6、保存和执行程序
l 在Python IDE中可以创建Python脚本程序,如下面:
name = raw_input("What is your name? ")
print "Hello, " + name + "!"
l 以.py为扩展名保存(如hello.py)
l 在命令行下执行:
python hello.py
l 在Windows中,可以双击.py文件,直接执行程序
l 在Linux/Unix中,需要在.py文件的开始追加:
#!/usr/bin/env python
l 并且要指定.py文件可执行权限:
$ chmod a+x hello.py
l 在.py文件中以“#”开始为注释,但上面那句是特例