PYTHON
语法特点
- 不需要声明数据类型 `a = 10`
- 代码语句不需要加分号 `print(‘hello world’)`
- 缩进决定代码块的范围,不需要大括号
一.基本数据类型
数值型 :整型,浮点型
字符串:str
布尔型:True / False
a = True
print(type(a))
常用容器
数据存储结构,能够更好管理数据
列表list:类似数组,索引从0开始,一个列表中可以存放不同数据类型的对象
listA = ['a', 'b', 2, True]
print(listA)
Append(内容):尾部插入内容
Insert(索引,内容):指定位置插入
del元素:删掉列表中的元素
listA = ['a', 'b', 2, True]
print(listA)
listA.append('123')
print(listA)
listA.insert(0, '123')
print(listA)
del listA[0]
print(listA)
print('a' in listA) #查找是否在列表里面
print(listA[1:3])#表示输出索引中1,2的元素
['a', 'b', 2, True]
['a', 'b', 2, True, '123']
['123', 'a', 'b', 2, True, '123']
['a', 'b', 2, True, '123']
True
['b', 2]
字典dict:以键值对的形式存储数据
通过键来访问值 所以键不可以重复
增加:dict[‘键’] = ‘值’
删除:del dict[’键‘]
改:直接修改
查:通过键值查
dictA = {'name':zhangsan, 'age':18}
dictA['school'] = 'bit'
del dictA['school']
dictA['name'] = 'list'
print(dictA['age'])
元组tuple:
集合set:
二.条件控制语句
if while 代码块
三.循环语句
while
for:可以遍历所有
四.函数
1.函数定义语法:
def函数名(参数列表):
代码段
return返回值 没有返回值 就会返回none
def sum(a, b):
c = a + b
return c
2.传参方式
- 位置传参
- 关键字传参 就和顺序无关
def temp(a, b, c):
print('a=%d' % a, end='\t')
print('b=%d' % b, end='\t')
print('c=%d' % c, end='\t')
temp(c=1,b=2,a=3)
五.文件读写
- 指定文件名
- 通过open创建一个文件对象
- 调用文件对象的相关方法执行读写操作
例子
– write(str):表示写入参数为字符串
writeline(list):参数为列表,将列表每个元素依次写入文件中
– read():无参数,读取全部内容
readline(size):读取一行,最多读取size字节
readline:按行读取
- 关闭文件 :文件名.close()
六.异常处理
处理方式:try-except
file_name = r'test.txt'
try:
file = open(file_name, 'r+')
result = file.read()
file.close()
except FileNotFoundError:
print('not found')
结果
not found
七.模块
重复利用已经有的命令 提高效率
- 模块的安装:pip install 模块名
- 模块的导入:import 模块名