Python 语法速通指南

1. 基础语法
1.1 表达式与常量
python
print(1 + 2 - 3)
print(1 + 2 * 3)
print(1 + 2 / 3) # 0.666...
1 + 2 - 3是表达式。1、2、3是字面值常量。+ - * /是运算符。- 先乘除,后加减。
- Python 中
1 / 2结果是0.5,不是0。
1.2 变量
python
a = 10
print(a)
a = 20
print(a)
a, b = 10, 20
a, b = b, a
print(a, b)
命名硬性规则:
- 由数字、字母、下划线组成。
- 不能数字开头。
- 不能和关键字重复。
- 大小写敏感。
软性建议:
- 使用有描述性的名字。
- 多个单词可用驼峰命名法:
totalCount、personInfo。
1.3 数据类型
python
a = 10
print(type(a)) # <class 'int'>
b = 0.5
print(type(b)) # <class 'float'>
c = 'hello'
print(type(c)) # <class 'str'>
d = True
print(type(d)) # <class 'bool'>
int:整数,范围理论上无上限。float:浮点数,相当于其他语言的 double。str:字符串,单引号或双引号都行。bool:布尔值,只有True和False。
字符串操作:
python
s = 'hello'
print(len(s)) # 5
print(s + 'world') # helloworld
⭐字符串不能和整数直接相加。
1.4 注释
python
# 单行注释
"""
文档字符串
也可以当多行注释使用
"""
1.5 输入输出
python
print('hello')
print(10)
print(True)
num = 10
print(f'num = {num}')
python
num = input('请输入一个整数:')
print(f'你输入的整数是 {num}')
input() 返回值一定是字符串类型。
类型转换:
python
a = input('请输入第一个整数:')
b = input('请输入第二个整数:')
a = int(a)
b = int(b)
print(f'a + b = {a + b}')
转换函数:
python
int()
float()
str()
bool()
1.6 运算符
算术运算符
python
7 / 2 # 3.5
7 // 2 # 3,地板除,向下取整
-7 // 2 # -4
7 % 2 # 1,求余数
4 ** 2 # 16,乘方
4 ** 0.5 # 2.0
注意:
/除数不能为 0。%是求余数,不是百分号。//是取整除法,不是四舍五入。**可以算整数次方,也可以算小数次方。
关系运算符
python
a = 10
b = 20
print(a < b)
print(a <= b)
print(a > b)
print(a >= b)
print(a == b)
print(a != b)
字符串也可以比较:
python
print('hello' < 'world')
浮点数不要直接用 == 判断相等:
python
print(0.1 + 0.2 == 0.3) # False
正确方式:
python
a = 0.1 + 0.2
b = 0.3
print(-0.000001 < (a - b) < 0.000001)
逻辑运算符
python
a = 10
b = 20
c = 30
print(a < b and b < c)
print(a < b and b > c)
print(a > b or b > c)
print(a < b or b > c)
print(not a < b)
print(not a > b)
短路求值:
python
print(10 > 20 and 10 / 0 == 1) # False,右侧不执行
print(10 < 20 or 10 / 0 == 1) # True,右侧不执行
链式比较:
python
a < b < c
# 等价于 a < b and b < c
赋值运算符
python
a = 10
b = 20
# 链式赋值
a = b = 10
# 多元赋值
a, b = 10, 20
复合赋值:
python
a = 10
a += 1 # a = a + 1
a -= 1
a *= 2
a /= 2
a //= 2
a %= 2
a **= 2
Python 不支持 ++ 和 --,用 += 1、-= 1。
2. 控制流
2.1 顺序语句
默认从上到下执行:
python
print('1')
print('2')
print('3')
结果一定是:
text
1
2
3
2.2 条件语句
语法:
python
if 条件:
代码块
elif 条件:
代码块
else:
代码块
示例:
python
choice = input('输入1表示认真学习,输入2表示躺平摆烂:')
if choice == '1':
print('你会找到好工作!')
elif choice == '2':
print('你可能毕业就失业了!')
else:
print('你的输入有误!')
注意:
if后面没有括号。- 条件后面有冒号
:。 - 用缩进表示代码块,通常是 4 个空格。
- 多条件分支用
elif,不是else if。
判断奇偶:
python
a = int(input('请输入一个整数:'))
if a % 2 == 0:
print('偶数')
else:
print('奇数')
判断正负数:
python
a = int(input('请输入一个整数:'))
if a > 0:
print('正数')
elif a < 0:
print('负数')
else:
print('为0')
判断闰年:
python
year = int(input('请输入年份:'))
if (year % 100 != 0 and year % 4 == 0) or year % 400 == 0:
print('闰年')
else:
print('平年')
pass 空语句:
python
if a != 1:
pass
else:
print('hello')
2.3 循环语句
while 循环
python
while 条件:
循环体
打印 1 到 10:
python
num = 1
while num <= 10:
print(num)
num += 1
计算 1 到 100 的和:
python
sum = 0
num = 1
while num <= 100:
sum += num
num += 1
print(sum)
计算 5 的阶乘:
python
result = 1
n = 1
while n <= 5:
result *= n
n += 1
print(result)
for 循环
python
for 循环变量 in 可迭代对象:
循环体
打印 1 到 10:
python
for i in range(1, 11):
print(i)
range 特点:
range(1, 11)表示[1, 11),即 1 到 10。- 第三个参数是步长:
python
for i in range(2, 12, 2):
print(i) # 2 4 6 8 10
倒序:
python
for i in range(10, 0, -1):
print(i)
求 1 到 100 的和:
python
sum = 0
for i in range(1, 101):
sum += i
print(sum)
continue 和 break
continue:结束本次循环,进入下一次。
python
for i in range(1, 6):
if i == 3:
continue
print(f'吃完第 {i} 个包子')
break:结束整个循环。
python
for i in range(1, 6):
if i == 3:
break
print(f'吃完第 {i} 个包子')
输入若干数字求平均值,遇到分号结束:
python
sum = 0
count = 0
while True:
num = input('请输入数字:')
if num == ';':
break
num = float(num)
sum += num
count += 1
print(sum / count)
3. 函数
3.1 定义函数
python
def 函数名(形参列表):
函数体
return 返回值
示例:
python
def calc_sum(beg, end):
total = 0
for i in range(beg, end + 1):
total += i
return total
print(calc_sum(1, 100))
print(calc_sum(300, 400))
⭐ 函数定义不会执行函数体,必须调用才会执行。
python
def test():
print('hello')
# 不调用就不执行
test()
函数必须先定义,再使用。
3.2 参数
形参:定义函数时写的参数。
实参:调用函数时传入的参数。
python
def test(a, b, c):
print(a, b, c)
test(10, 20, 30)
⭐ 形参和实参个数要匹配。
Python 是动态类型,形参不必指定类型:
python
def test(a):
print(a)
test(10)
test('hello')
test(True)
3.3 返回值
python
def calc_sum(beg, end):
total = 0
for i in range(beg, end + 1):
total += i
return total
result = calc_sum(1, 100)
print(result)
一个函数可以有多个 return:
python
def is_odd(num):
if num % 2 == 0:
return False
return True
返回多个值:
python
def get_point():
x = 10
y = 20
return x, y
a, b = get_point()
print(a, b)
⭐ 返回多个值本质上是返回元组。
3.4 变量作用域
局部变量:函数内部定义。
全局变量:函数外部定义。
python
x = 20
def test():
x = 10
print(f'函数内部 x = {x}')
test()
print(f'函数外部 x = {x}')
如果想在函数内部修改全局变量,用 global:
python
x = 20
def test():
global x
x = 10
test()
print(x)
if / while / for 不会产生新的作用域。
3.5 默认参数与关键字参数
默认参数:
python
def add(x, y, debug=False):
if debug:
print(f'调试信息:x={x}, y={y}')
return x + y
print(add(10, 20))
print(add(10, 20, True))
⭐ 带有默认值的参数要放在没有默认值的参数后面。
关键字参数:
python
def test(x, y):
print(f'x = {x}')
print(f'y = {y}')
test(x=10, y=20)
test(y=100, x=200)
3.6 递归
递归:函数自己调用自己。
python
def factor(n):
if n == 1:
return 1
return n * factor(n - 1)
print(factor(5)) # 120
⭐ 递归必须有结束条件,并且每次递归要逼近结束条件,否则会栈溢出。
4. 容器
4.1 列表 list
创建列表:
python
alist = []
alist = list()
alist = [1, 2, 3, 4]
列表元素可以是不同类型:
python
alist = [1, 'hello', True]
访问下标:
python
alist = [1, 2, 3, 4]
print(alist[2]) # 3
print(alist[-1]) # 4
修改元素:
python
alist[2] = 100
print(alist)
下标越界会报错:
python
# print(alist[100]) # IndexError
获取长度:
python
print(len(alist))
切片:
python
alist = [1, 2, 3, 4]
print(alist[1:3]) # [2, 3]
print(alist[1:]) # [2, 3, 4]
print(alist[:2]) # [1, 2]
print(alist[:]) # [1, 2, 3, 4]
切片步长:
python
alist = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
print(alist[::2]) # [1, 3, 5, 7, 9]
print(alist[::-1]) # 倒序
遍历列表:
python
alist = [1, 2, 3, 4]
for elem in alist:
print(elem)
按下标遍历:
python
for i in range(len(alist)):
print(alist[i])
新增元素:
python
alist = [1, 2, 3, 4]
alist.append('hello') # 尾插
alist.insert(1, 'world') # 指定下标插入
print(alist)
查找元素:
python
alist = [1, 2, 3, 4]
print(2 in alist) # True
print(10 in alist) # False
print(alist.index(2)) # 1
删除元素:
python
alist = [1, 2, 3, 4]
alist.pop() # 删除末尾
alist.pop(2) # 删除下标 2
alist.remove(2) # 按值删除
print(alist)
连接列表:
python
alist = [1, 2, 3, 4]
blist = [5, 6, 7]
print(alist + blist) # 生成新列表
alist.extend(blist) # 把 blist 拼接到 alist 后面
print(alist)
print(blist)
4.2 元组 tuple
创建元组:
python
atuple = ()
atuple = tuple()
atuple = (1, 2, 3)
元组不能修改:
python
atuple = (1, 2, 3)
# atuple[0] = 100 # 报错
支持读操作:下标、切片、遍历、in、index、+。
不支持写操作:修改、新增、删除、extend。
元组常用于函数返回多个值:
python
def get_point():
return 10, 20
result = get_point()
print(type(result)) # <class 'tuple'>
列表 vs 元组:
- 列表可变,适合元素需要改变的场景。
- 元组不可变,适合元素不需要改变、更安全的场景。
- 元组可以作为字典的键,列表不行。
4.3 字典 dict
字典存储键值对:
python
student = {
'id': 1,
'name': 'zhangsan',
'score': 80
}
创建空字典:
python
a = {}
b = dict()
查找 key:
python
print('id' in student)
print(student['id'])
print(student['name'])
⭐ key 不存在时,用 [] 取值会报错。
新增 / 修改:
python
student['score'] = 90 # 不存在则新增,存在则修改
print(student)
删除:
python
student.pop('score')
print(student)
遍历:
python
for key in student:
print(key, student[key])
取出所有 key 和 value:
python
print(student.keys())
print(student.values())
5. 文件操作
5.1 打开与关闭
python
f = open('d:/test.txt', 'r')
f.close()
打开方式:
'r':读'w':写,会清空原文件'a':追加写
5.2 写文件
python
f = open('d:/test.txt', 'w')
f.write('hello')
f.close()
追加写:
python
f = open('d:/test.txt', 'a')
f.write('world')
f.close()
结果:helloworld
5.3 读文件
python
f = open('d:/test.txt', 'r')
result = f.read(2)
print(result)
f.close()
按行读取:
python
f = open('d:/test.txt', 'r')
for line in f:
print(f'line = {line}', end='')
f.close()
读取所有行:
python
f = open('d:/test.txt', 'r')
lines = f.readlines()
print(lines)
f.close()
5.4 使用 with 自动关闭
python
with open('d:/test.txt', 'r', encoding='utf8') as f:
lines = f.readlines()
print(lines)
⭐ 中文文件建议指定编码:
python
open('d:/test.txt', 'r', encoding='utf8')
6. 使用库
6.1 标准库
python
import datetime
date1 = datetime.datetime(2012, 2, 14)
date2 = datetime.datetime(2022, 7, 12)
print(date2 - date1)
字符串常用方法:
python
s = 'I am a student.'
tokens = s.split()
tokens.reverse()
print(' '.join(tokens))
判断前缀:
python
print('abc'.startswith('ab'))
文件查找:
python
import os
input_path = input('请输入待搜索路径:')
pattern = input('请输入待搜索关键词:')
for dirpath, dirnames, filenames in os.walk(input_path):
for f in filenames:
if pattern in f:
print(f'{dirpath}/{f}')
6.2 第三方库与 pip
安装:
bash
pip install 库名
示例:
bash
pip install qrcode[pil]
pip install xlrd==1.2.0
pip install pynput==1.6.8
pip install playsound==1.2.2
pip install pyinstaller
生成二维码:
python
import qrcode
img = qrcode.make('hello')
img.save('qrcode.png')
⭐ 如果 pip 安装后 PyCharm 仍找不到模块,检查:
text
Settings -> Project -> Python Interpreter
6.3 打包 exe
bash
pyinstaller -F 学生管理系统.py
-F 表示打包成单个 exe 文件。
7. 速查表
常用内置函数
| 函数 | 作用 |
|---|---|
print() |
输出 |
input() |
输入,返回字符串 |
type() |
查看类型 |
len() |
长度 |
int() / float() / str() / bool() |
类型转换 |
range() |
生成序列 |
open() |
打开文件 |
常用运算符
| 运算符 | 含义 |
|---|---|
+ - * / |
加减乘除 |
// |
地板除 |
% |
求余 |
** |
乘方 |
== != < <= > >= |
关系比较 |
and or not |
逻辑运算 |
= |
赋值 |
+= -= *= /= //= %= **= |
复合赋值 |
容器对比
| 类型 | 是否可变 | 表示 | 特点 |
|---|---|---|---|
| list | 可变 | [] |
有序,可增删改 |
| tuple | 不可变 | () |
有序,不可改,可作字典键 |
| dict | 可变 | {} |
键值对,按键查找 |
8. 易错点复习清单
- 代码标点必须是英文。
- 缩进决定代码块,通常 4 个空格。
-
input()返回字符串,计算前要转换类型。 -
/结果是小数,//是向下取整。 -
%是求余数。 - 浮点数不要直接用
==比较。 -
and/or有短路求值。 - 函数先定义再调用。
- 函数内部修改全局变量要用
global。 - 默认参数要放在无默认参数后面。
- 列表可变,元组不可变。
- 字典用
[]取不存在的 key 会报错。 - 文件读写注意
r/w/a。 - 中文文件注意
encoding='utf8'。 - pip 安装后检查 PyCharm 解释器。
- Python 没有
++/--。
Python 语法不难,难点在于多写、多调试、多查文档。
记住:代码第一目标是容易理解,第二目标才是执行正确。