🐍 Python 基础语法规则(Python 3)
1. 缩进(Indentation)——最重要的规则!
Python 使用 缩进来表示代码块,而不是 {} 或 begin/end。
if 5 > 2:
print("5 大于 2") # 必须缩进(通常用 4 个空格)
✅ 正确:
if True:
print("hello")
if False:
print("world")
❌ 错误(缩进不一致):
if True:
print("hello") # 报错:IndentationError
⚠️ 建议:始终使用 4 个空格缩进,不要混用 Tab 和空格。
2. 注释(Comments)
## 单行注释
"""
多行字符串(常用于文档说明)
"""
'''
也可以这样写多行注释
'''
3. 变量与赋值
不需要声明类型
使用 = 赋值
x = 10
name = "Alice"
is_student = True
pi = 3.14
✅ 动态类型:
x = 5
x = "hello" # 合法,变量可以改变类型
✅ 多变量赋值:
a, b, c = 1, 2, 3
x = y = 0 # 同时赋值
4. 数据类型
类型 示例
int 5, -3
float 3.14, -0.5
str "hello", 'world'
bool True, False
None None(空值)
查看类型:
type(5) # <class 'int'>
type("abc") # <class 'str'>
5. 字符串(String)
s1 = "Hello"
s2 = 'World'
s3 = f"Hello {name}" # f-string(推荐)
s4 = "Hello " + name # 拼接
s5 = s1 * 3 # "HelloHelloHello"
常用方法:
"hello".upper() # "HELLO"
" Hello ".strip() # "Hello"
"hi".replace("h", "H") # "Hi"
"one,two".split(",") # ['one', 'two']
6. 运算符
类型 运算符 示例
算术 +, -, *, /, //, %, ** 5 // 2 = 2, 5 % 2 = 1, 2**3 = 8
比较 ==, !=, >, <, >=, <= 5 == 5 → True
逻辑 and, or, not (5 > 3) and (2 < 4)
成员 in, not in 'a' in 'abc' → True
身份 is, is not x is None
7. 控制流
✅ if-elif-else
if x > 10:
print("大")
elif x == 10:
print("等于")
else:
print("小")
✅ for 循环
for i in range(5): # 0,1,2,3,4
print(i)
for char in "hello":
print(char)
for item in [1, 2, 3]:
print(item)
✅ while 循环
i = 0
while i < 5:
print(i)
i += 1
✅ break 和 continue
for i in range(10):
if i == 3:
continue # 跳过本次
if i == 7:
break # 退出循环
print(i)
8. 数据结构
✅ 列表(List)——有序、可变
lst = [1, 2, 3]
lst.append(4)
lst[0] = 0
print(lst[1]) # 2
✅ 元组(Tuple)——有序、不可变
t = (1, 2, 3)
print(t[0]) # 1
# t[0] = 5 # ❌ 报错
✅ 字典(Dictionary)——键值对
d = {"name": "Alice", "age": 20}
d["city"] = "Beijing"
print(d["name"])
✅ 集合(Set)——无序、唯一
s = {1, 2, 3}
s.add(4)
s.add(1) # 重复无效
9. 函数(Function)
def greet(name, age=18):
return f"Hello {name}, you are {age}"
result = greet("Bob")
print(result)
def 定义函数
可设默认参数
return 返回值
10. 类与对象(OOP)
class Dog:
def __init__(self, name):
self.name = name
def bark(self):
print(f"{self.name} says woof!")
dog = Dog("Buddy")
dog.bark() # Buddy says woof!
__init__ 是构造函数
self 表示实例自身
11. 异常处理
try:
x = 10 / 0
except ZeroDivisionError:
print("不能除以零!")
except Exception as e:
print(f"错误: {e}")
else:
print("没有异常")
finally:
print("总是执行")
12. 文件操作
# 写入文件
with open("test.txt", "w") as f:
f.write("Hello World\n")
# 读取文件
with open("test.txt", "r") as f:
content = f.read()
print(content)
with 自动关闭文件
模式:r读,w写(覆盖),a追加
13. 导入模块
import math
from datetime import datetime
import numpy as np # 常见缩写
print(math.sqrt(16))
print(datetime.now())
14. 常用内置函数
函数 说明
print() 输出
input() 输入(返回字符串)
len() 长度
type() 类型
str(), int(), float() 类型转换
range(5) 生成 0~4
list(), dict(), set() 创建容器
15. 代码风格建议(PEP 8)
变量名:snake_case(如 user_name)
类名:PascalCase(如 StudentInfo)
常量:UPPER_CASE(如 PI = 3.14)
每行不超过 79 字符
使用空行分隔函数和类
✅ 小练习(巩固记忆)
# 任务:打印 1 到 10 的平方,跳过偶数
for i in range(1, 11):
if i % 2 == 0:
continue
print(f"{i} 的平方是 {i**2}")
📚 推荐学习资源
官方文档:https://docs.python.org/3/
菜鸟教程:https://www.runoob.com/python/python-tutorial.html
廖雪峰 Python 教程:https://www.liaoxuefeng.com/wiki/1016959605405280
861

被折叠的 条评论
为什么被折叠?



