Python 基础语法学习文档
1. Python简介
- 解释型语言:无需编译,逐行执行
- 动态类型:变量类型在运行时确定
- 代码简洁:缩进代替大括号,可读性高
- 跨平台:支持Windows/macOS/Linux
2. 安装与环境
- 官网下载:www.python.org
- 验证安装:
python --version - 推荐使用虚拟环境:
python -m venv myenv
3. 基础语法结构
变量与数据类型
a = 10 # 整数 int
b = 3.14 # 浮点数 float
c = "Hello" # 字符串 str
d = True # 布尔值 bool (True/False)
e = None # 空值 NoneType
注释
# 单行注释
"""
多行注释
三个引号实现
"""
4. 输入与输出
输出
print("Hello World") # 基本输出
print("Name:", name, "Age:", age) # 多参数输出
格式化输出
# f-string (推荐)
print(f"Result: {result:.2f}")
# format方法
print("{} + {} = {}".format(a, b, a+b))
# 传统方式
print("Value: %.2f" % 3.1415926)
输入
name = input("请输入姓名:")
age = int(input("请输入年龄:")) # 类型转换
5. 运算符
| 类型 | 运算符 | |
|---|---|---|
| 算术 | + - * / // % ** | |
| 比较 | == != > < >= <= | |
| 逻辑 | and or not | |
| 赋值 | = += -= *= /= | |
| 位运算 | `& | ^ ~ << >>` |
| 成员 | in、not in | |
| 身份 | is、is not |
6. 流程控制
条件语句
if score >= 90:
print("A")
elif score >= 80:
print("B")
else:
print("C")
循环结构
while循环:
count = 0
while count < 5:
print(count)
count += 1
for循环:
for i in range(5): # 0-4
print(i)
for char in "hello": # 遍历字符串
print(char)
循环控制
break # 终止循环
continue # 跳过本次循环
pass # 占位语句(空操作)
7. 数据结构
列表 List
fruits = ["apple", "banana", "cherry"]
fruits.append("orange") # 添加元素
print(fruits[1]) # 访问元素 → "banana"
元组 Tuple
colors = ("red", "green", "blue") # 不可变
集合 Set
s = {1, 2, 3} # 无序不重复
s.add(4) # 添加元素
字典 Dictionary
person = {
"name": "Alice",
"age": 30,
"city": "New York"
}
print(person["name"]) # 访问值 → "Alice"
推导式
# 列表推导式
squares = [x**2 for x in range(10)]
# 字典推导式
square_dict = {x: x**2 for x in range(5)}
8. 字符串处理
基本操作
s = "Python"
print(s[0]) # 'P'
print(s[2:5]) # 'tho'(切片)
print(len(s)) # 获取长度 → 6
常用方法
"hello".upper() # → "HELLO"
"WORLD".lower() # → "world"
" python ".strip() # → "python"
"a,b,c".split(",") # → ['a', 'b', 'c']
"-".join(["2023", "08", "01"]) # → "2023-08-01"
9. 函数
定义与调用
def add(a, b):
"""返回两个数的和"""
return a + b
result = add(3, 5) # → 8
参数类型
# 默认参数
def greet(name="Guest"):
print(f"Hello {name}")
# 可变参数
def sum_all(*numbers):
return sum(numbers)
作用域
global_var = 10
def test():
local_var = 20
print(global_var) # 访问全局变量
Lambda函数
square = lambda x: x**2
print(square(5)) # → 25
10. 文件操作
基本读写
# 写入文件
with open("test.txt", "w") as f:
f.write("Hello World")
# 读取文件
with open("test.txt", "r") as f:
content = f.read()
打开模式
r: 只读(默认)w: 写入(覆盖)a: 追加b: 二进制模式
11. 异常处理
try:
result = 10 / 0
except ZeroDivisionError:
print("不能除以零!")
except Exception as e:
print(f"发生错误:{e}")
else:
print("无异常时执行")
finally:
print("始终执行")
12. 模块与包
导入模块
import math
print(math.sqrt(16)) # → 4.0
from datetime import datetime
print(datetime.now())
自定义模块
# mymodule.py
def say_hello():
print("Hello!")
# main.py
import mymodule
mymodule.say_hello()
13. 面向对象编程
类与对象
class Dog:
def __init__(self, name):
self.name = name
def bark(self):
print("汪汪!")
my_dog = Dog("Buddy")
my_dog.bark() # 输出:汪汪!
继承
class Bulldog(Dog):
def run(self):
print("快速奔跑!")
14. 常用内置函数
| 函数 | 说明 |
|---|---|
len() | 返回对象长度 |
type() | 返回对象类型 |
range() | 生成整数序列 |
sorted() | 返回排序后的新列表 |
enumerate() | 返回枚举对象(索引+元素) |
学习建议
- 多动手编写代码
- 使用Python交互式环境练习
- 阅读官方文档:docs.python.org/3/
- 实践小项目(计算器、待办清单等)
通过系统学习这些基础内容,您将掌握Python编程的核心技能,为后续进阶学习打下坚实基础。