编程规范
- 代码开头
Python中的代码必须顶格编写,除非被作为语句嵌套在条件判断或者条件循环中 - 代码层级
第一层顶格编写,第二层开头需要预留四个空格(不考虑跨平台可以使用tab) - 对齐方式
同一个层级的代码必须严格对齐(第一层对齐,第二层四个空格,第三层8个空格) - 注释
单行注释:#
多行注释:首尾处用三对引号,“”“注释”“”,‘’‘注释’‘’ - 代码块
逻辑判断if以及循环条件while和for条件后均以冒号结尾,然后通过四个空格开始下一层级的实际执行动作语句编写(冒号后面接上的语句是代码块)
如
score = 50
if score < 60:
print("不及格")
elif score < 70:
print("中等")
elif score < 80:
print("良好")
else:
print("优秀")
基本数据类型
- Python中的变量不需要声明
- 变量赋值以后才会被创建
- 所说的类型是变量所指的内存中对象的类型
- 基本数据类型包括:Number(数字)、String(字符串)、List(列表)、Tuple(元组)、Set(集合)、Dictionary(字典)
其中六个基本数据类型,又分为不可变数据(Number、String、Tuple)和可变数据(List、Set、Dictionary)
Number(数值型数据)
数字数据类型用于存储数值
数据类型 | 存储的数值 |
---|---|
int | 整数类型 |
float | 浮点类型 |
bool | 布尔类型 |
complex | 复数类型 |
相关操作
函数 | 含义 |
---|---|
type() | 查询变量所指的对象类型 |
isinstance() | 判断变量所指类型是否是某类型 |
del() | 删除变量 |
如
a = 1
print(type(a)) #<class 'int'>
print(isinstance(a,int)) #True
print(isinstance(a,float)) #False
print(isinstance(a,bool)) #False
print(isinstance(a,complex)) #False
del(a) #
print(a) # NameError: name 'a' is not defined
String(字符串)
- 字符串使用单引号‘’或者“”括起来
- 使用反斜杠\ 转义特殊字符
- 不让反斜杠转义,在字符串前面添加一个r
- 索引值以0为开始值,-1为从末尾的开始位置
- ‘+’ 进行字符串连接
- 字符串不能发生改变
# str='i'm ok' 错误 SyntaxError: invalid syntax
str="I'm ok"
print(str)
print(str[2]) # m
print(str[-1]) # k
print(str + str)# I'm okI'm ok
print('I\'m ok') # I'm ok
print(r'I\'m ok') # I\'m ok
str[1]='a' # TypeError: 'str' object does not support item assignment
List(列表)
- 一种有序集合
- 元素类型可以是不相同的(数字、字符串、列表)
- 可随时添加和删除其中的元素
- append
- insert
- pop
- 和字符串一样,可以被索引和切片
- ‘+’ 是列表连接
- 元素可变
note = ["apple","banana","pear","peach"] # 赋值
print(note) # ['apple', 'banana', 'pear', 'peach']
print(len(note)) # 4
print(note[0])# 按索引访问list中第一个元素apple
print(note[1])# 按索引访问list中第二个元素banana
print(note[-1])# 按索引访问list中倒数第一个元素peach
print(note[-2])# 按索引访问list中倒数第二个元素pear
note.append("melon") #列表末尾追加元素
print(note) # ['apple', 'banana', 'pear', 'peach', 'melon']
# 元素插入到指定的位置,比如插入到索引为1的位置
note.insert(1, "grape")
print(note) # ['apple', 'grape', 'banana', 'pear', 'peach', 'melon']
# 删除list末尾的元素
note.pop()
print(note) # ['apple', 'grape', 'banana', 'pear', 'peach']
# 删除list指定位置的元素
note.pop(1)
print(note) # ['apple', 'banana', 'pear', 'peach']
# 替换元素
note[0] = "water-melon"
print(note) # ['water-melon', 'banana', 'pear', 'peach']
# list中的元素可以不同
l=["apple", 12, True, ""]
print(l) # ['apple', 12, True, '']
Tuple(元组)
- 元组写在小括号()中,元素之间用逗号隔开
- 与字符串一样,依然可以索引和切片
- 元组的元素不可以改变,但可以包含可变对象(如list)
- 构造单元素的元组,需要额外注意逗号
- 可以使用+进行拼接
# 因为元组不可变,元组没有append()、insert()、pop()方法
note=("apple","pear","grape")
# 同样可以采用list获取元素的方法
print(note[1]) # pear
# 当定义只有一个元素的元组时,不能写成t=(1),而应该写成t=(1,)
t = (1,)
print(t) # (1,)
t2 = (1)
print(tu) # 1
# 元组的元素不可以改变,但可以包含可变对象(如list)
t3 = ("apple","grape",["melon","pear"])
print(t3) # ('apple', 'grape', ['melon', 'pear'])
t3[2][0] = "a"
t3[2][1] = "b"
print(t3) # ('apple', 'grape', ['a', 'b'])
dictionary(字典)
- {key1:value1,key2:value2,…}
- 是一种无序的键值组合,通过键来存取,列表是一种有序的对象集合,通过便宜来存取
- 同一个字典中,键(key)必须是唯一的
- 创建空字典:{}
d={'key1':1,'key2':2,'key3':3}
print(d['key1']) #1
# 查看key是否在字典里
print('key4' in d) # False
print('key3' in d) # True
d.get('key4') # key不存在,返回None时,交互环境并没有显示
# 可以在key不存在的情况下指定返回值
print(d.get('key4',-1)) # -1
print(d.get('key3',-1)) # 3
# 删除key
d.pop('key2')
print(d) # {'key1': 1, 'key3': 3}
d['key4'] = [1,2,3]
print(d)
key5 = [1,2,3]
# 列表不能作为字典中的key
d[key5] = 'list' # TypeError: unhashable type: 'list'
Set(集合)
- 不重复元素组成的集合
- 基本功能是进行成员关系测试和删除重复元素
- 创建集合使用大括号{} or set()
- 空集合创建只能使用set(),不能使用{},{}是创建空字典的
- 集合操作
- 交集
- 并集
- 差集
# 定义一个set
s = set([1,2,3,4,4,5,5,6,6])
print(s) # {1, 2, 3, 4, 5, 6} 重复的元素会被过滤掉
s.add(6) # 添加重复元素,不会有效果
print(s) # {1, 2, 3, 4, 5, 6}
s.add(7)
print(s) # {1, 2, 3, 4, 5, 6, 7}
# 删除元素
s.remove(1)
print(s) # {2, 3, 4, 5, 6, 7}
# 集合间的交并集
s1 = set([1,2,3])
s2 = set([2,3,4])
print(s1 & s2) #交集{2, 3}
print(s1 | s2) #并集{1, 2, 3, 4}
print(s1 - s2) #s1与s2的差集{1}
print(s2 - s1) #s2与s1的差集{4}
数据类型转换
函数 | 作用 |
---|---|
int(x) | x转换成一个整数 |
float(x) | x转换成一个浮点数 |
str(x) | x转换成字符串 |
tuple(s) | 序列s转换成一个元组 |
list(s) | 序列s转换成一个列表 |
set(s) | 转换为可变集合 |
dict(d) | 创建一个字典,d必须是一个(key,value)元组 |
文件操作
读文件
打开文件open()
读取文件read()
关闭文件close()
# 读文件,使用python内置的open()函数
f = open('./test.txt','r') # 'r'表示读
# 文件打开成功,调用read()方法可以一次读取文件的全部内容
print(f.read())
# 最后通过文件调用close()方法关闭文件,文件不关闭会占用操作系统资源,同时操作系统同一时间能打开的文件数量也是有限的
f.close()
# 当文件读写时可能产生IOError,一旦出错,后面文件的关闭就不会调用,为了无论是否出错都能正确的关闭文件,可以使用try...finally来实现
try:
f = open('./test.txt','r')
print(f.read())
finally:
if f:
f.close()
# 上面的代码比较繁琐,python引入了with语句自动调用close()
with open('./test.txt','r') as f:
print(f.read())
read()会一次读取文件的全部内容
readlines()一次读取文件所有内容并按行返回list
with open('./test.txt','r') as f:
for line in f.readlines():
print(line.strip()) # 把末尾的'\n'删掉,strip() 方法用于移除字符串头尾指定的字符(默认为空格或换行符)或字符序列。该方法只能删除开头或是结尾的字符,不能删除中间部分的字符。
读取特定文件
读取二进制文件
with open("./test.jpg","rb") as f:
print(f.read()) # 输出的是十六进制表示的字节
读取字符编码文件
with open("./gbk.txt",encoding='gbk') as f:
print(f.read())
遇到编码错误后如何处理
# 最简单的方式就是直接忽略
with open("./gbk.txt","r",encoding="gbk",errors="ignore") as f:
print(f.read())
写文件
- 在调用open()函数时,传入标识符‘w’或者‘wb’表示写文本文件或者写二进制文件
- ‘w’会直接复写之前的内容,‘a’可以以追加的形式写入
- 同理,写入特定编码的文本文件,就给open()函数传入encoding函数,将字符串自动转换成指定编码
with open("./gbk.txt","w") as f:
w.write("hello world")
with open("./gbk.txt","a") as f:
w.write("hello world")
with open("./gbk.txt",'w',encoding='gbk') as f:
w.write("hello world")
基本语法
条件判断
x=int(input("birth:")) # input输入的为字符串类型,需要转成int类型
if x < 2000:
print("00前")
else:
print("00后")
当有两个或两个以上的判断语句时,需要使用elif判断
score = 50
if score < 60:
print("不及格")
elif score < 70:
print("中等")
elif score < 80:
print("良好")
else:
print("优秀")
分支循环for
# 遍历list输出list中的元素
fruits = ["apple","banana","melon"]
for fruit in fruits:
print(fruit)
# 0-100求和
sum = 0
for i in range(101):
sum += i
print(sum)
分支循环while
sum = 0
n=100
while n > 0:
sum += n
n = n - 1
print(sum)