基本对象类型
- 字符串(string),简记str ,使用‘’或“”括起来的一系列字符
- 整数(integer),简记int,十进制:21 八进制:025 十六进制:0x15
- 浮点数(float),5.23, 3.14
- 布尔数(boolean),简记 bool,布尔运算 Ture False
- 复数(complex) 1+1j
对象类型差异
- 类型不同,运算规则不同
- 在计算机中表示方式不同
浮点数
- 表示能力更强
- 有精度损失
- CPU 有专门的浮点数运算部件
强制类型转换
- 字符串变整数 int(‘1234’)——1234
- 整数变字符串 str(123)——‘123’
- 字符串变浮点数 float(“123”)——123.0
- 整数变浮点数 float(123)——123.0
- 整数变布尔数 bool(123)——true bool(0)——false
算术运算符
注意事项
- Python 2 中,“/”表示向下取整除(floor division)
- 两个整数相除,结果也是整数,舍去小数部分
- 如果有一个数为浮点数,则结果为浮点数
- 自动类型转换 bool -- int --float -- complex
模块(model)
- 实现一定的功能的 Python 脚本集合
- 引入模块 import module_name
import math #引入模块 dir(math) # 查看模块内容 ['__doc__', '__name__', '__package__', 'acos', 'acosh', 'asin', 'asinh', 'atan', 'atan2', 'atanh', 'ceil', 'copysign', 'cos', 'cosh', 'degrees', 'e', 'erf', 'erfc', 'exp', 'expm1', 'fabs', 'factorial', 'floor', 'fmod', 'frexp', 'fsum', 'gamma', 'hypot', 'isinf', 'isnan', 'ldexp', 'lgamma', 'log', 'log10', 'log1p', 'modf', 'pi', 'pow', 'radians', 'sin', 'sinh', 'sqrt', 'tan', 'tanh', 'trunc'] help(math.sin) #查看某个脚本的帮助 Help on built-in function sin in module math: sin(...) sin(x) Return the sine of x (measured in radians).
关系运算符
- 判断一个数 x 是否为偶数
- 用于判断两个值的关系
- 运算的结果只有两种(布尔型)
逻辑运算符
- 如果年份 y 能被 4 整除但是不能被 100 整除,或者能被 400 整除,则是闰年。
2014、 1900 年不是闰年
2012、 2000 年是闰年 (y % 4 == 0 and y % 100 != 0) or (y % 400 == 0)
运算符优先级
变量
- 用于引用(绑定)对象的标识符
- 语法 用于引用(绑定)对象的标识符
增量赋值运算符
- x = x + 1
- x += 1
标识符(Identifier)
- 变量,函数,模块等的名字
- 命名规则
- 可以任意长
包含数字和字母、 下划线
但首个必须是字母或下划线
大小写敏感
标识符不能是关键字
关键字
标准(键盘)输入
- raw_input 函数
- 功能:读取键盘输入,将所有输入作为字符串看待
- 语法:raw_input([prompt]) [prompt]是提示符,最好提供
- 举例:
radius = float(raw_input('Radius: '))
标准控制台输入
- print 关键字
- 功能:将对象的值输出到控制台上
- 语法:print object or variable
- 举例:print area
- 多个对象输出到一行
print 'The area for the circle of radius', radius, 'is', area
- 转义符
- \n
- \t
- \\
- \a
- \'
- \''
小练习
x = float(raw_input('x:'))
runnian = (x % 4 == 0 and x % 100 != 0) or (x % 400 == 0)
if runnian == True :
print x, '是闰年'
else:
print x, '不是闰年'