python是由python解释器独立解释不需要 编译的脚本文件
基础操作
在python中 运算符和变量定义几乎与C 及其其他变成语言相同;
if语句
举例
if expression:
if_suite
else:
else_suite
if语句支持 elif 循环
while语句
举例:
while expression:
while_suite
for语句
for语句与shell中相似,是由一个内建的迭代器来完成 for语句的循环
举例:
for i in [ table ] :
for_suite
python字符串
使用引号(包含 单引号 双引号 或者三引号 )定义一组可以包含 数字,字母,符号(非特殊系统符号)的集合
可以使用 索引来 取值,第一位的索引值为0 最后一位的索引值为 -1
如:
>>> a='abcd'
>>> a[0]
'a'
>>> a[1]
'b'
>>> a[2]
'c'
切片取值
如:
>>> b='123456'
>>> b[1:5]
'2345'
>>> b[:5]
'12345'
序列类型:可以使用索引和切片来取值
序列的基本操作:
len()
求序列长度
+ 连接两个序列
* 重复序列元素
in 判断元素是否在序列中
max() 返回最大值
min() 返回最小值
cmp(tuple1, tuple2) 比较两个序列值是否相同
元组
使用()圆括号中用逗号分割的项目定义
元组的值不可改变
内存存储空间是不同的
举例:
>>> a=("wxh",32,"man")
>>> a[0]
'wxh'
>>> a[1]
32
>>> a[2]
'man'
>>> t1=() 空元组
>>> t2=(2,) 单一元组
>>> t3=(3)
>>> type(t1)
<type 'tuple'>
>>> type(t2)
<type 'tuple'>
>>> type(t3)
98<type 'int'>
列表操作: 内存储存空间相同
索引和切片
添加
删除
修改
查找
举例:
>>> list=['wxh',32,'man']
>>> list
['wxh', 32, 'man']
>>> list[0]
'wxh'
>>> list[1]
32
>>> list[2]
'man'
>>> list[0:2]
['wxh', 32]
>>> list
['wxh', 32, 'man']
>>> list[0]
'wxh'
>>> list[0]='tom'
>>> list
['tom', 32, 'man']
>>> id(list)
38164240
>>> list[1]=30
>>> list
['tom', 30, 'man']
>>> id(list)
38164240
字典
是 python 中唯一的映射类型(哈希表)无序的
字典对象是可变的,但是字典的键必须是不可变对象,并且一个字典中可以使用不
同类型的键值
字典举例
>>> dict1={'name':'wxh','age':'32','gender':'male'}
>>> id(dict1)
39342464
>>> dict1['name']
'wxh'
>>> dict1['age']
'32'
>>> dict1['gender']
'male'
>>> dict1[0]
keys()返回键列表
values()返回值列表
items()返回包含键值对的元组
字典更新删除
del dict1['tel'] 删除字典中键值为 tel 的元素
dict1.pop('tel') 删除并且返回键为 tel 的元素
dict1.clear() 删除字典所有元素
del dict1 删除整个字典
字典的其他方法
dict.fromkeys(seq,val=None) 以 seq 中的元素为键值并返回一个字典,val 为制定的
默认值
dict.get(key,'error') 返回 key 的 value,如果该键不存在返回定制的值 error
dict.has_key(key) 判断字典中是否存在 key,建议使用 in 和 not in 代替
dict.items() 返回键值对元组的列表
dict.keys() 返回字典中键的列表
dict.setdefault(key,'hello') 若 key 存在返回其值,不存在则设置其值为定制值 hello
dict.update(dict2) 将 dict2 中的键值对添加到字典 dict 中,如果有重复覆盖,原字典
不存在的条目添加进来
dict.values() 返回字典中所有值的列表