Python 基础语法全面指南
Python 是一种高级、解释型、通用的编程语言,以其简洁的语法和强大的功能而闻名。本文将全面介绍 Python 的基础语法,适合初学者快速掌握 Python 编程的核心概念。
1. Python 基础
1.1 第一个 Python 程序
# 这是一个简单的Python程序
print("Hello, World!") # 输出: Hello, World!
1.2 注释
# 这是单行注释
"""
这是多行注释
可以跨越多行
"""
'''
这也是多行注释
使用单引号
'''
2. 变量与数据类型
2.1 变量
# 变量赋值
x = 5 # 整数
y = 3.14 # 浮点数
name = "Alice" # 字符串
is_active = True # 布尔值
print(x, y, name, is_active) # 输出: 5 3.14 Alice True
2.2 基本数据类型
# 整数
a = 10
b = -5
# 浮点数
pi = 3.14159
temperature = -10.5
# 字符串
s1 = '单引号字符串'
s2 = "双引号字符串"
s3 = """多行
字符串"""
# 布尔值
t = True
f = False
# 空值
n = None
print(type(a), type(pi), type(s1), type(t), type(n))
# 输出: <class 'int'> <class 'float'> <class 'str'> <class 'bool'> <class 'NoneType'>
2.3 类型转换
# 显式类型转换
num_str = "123"
num_int = int(num_str) # 字符串转整数
num_float = float(num_str) # 字符串转浮点数
str_num = str(123) # 数字转字符串
print(num_int, num_float, str_num) # 输出: 123 123.0 '123'
3. 运算符
3.1 算术运算符
a = 10
b = 3
print(a + b) # 加法 13
print(a - b) # 减法 7
print(a * b) # 乘法 30
print(a / b) # 除法 3.333...
print(a // b) # 整除 3
print(a % b) # 取模 1
print(a ** b) # 幂运算 1000
3.2 比较运算符
x = 5
y = 8
print(x == y) # False
print(x != y) # True
print(x > y) # False
print(x < y) # True
print(x >= y) # False
print(x <= y) # True
3.3 逻辑运算符
a = True
b = False
print(a and b) # False
print(a or b) # True
print(not a) # False
3.4 赋值运算符
x = 5
x += 3 # 等同于 x = x + 3
print(x) # 8
x -= 2 # 等同于 x = x - 2
print(x) # 6
x *= 4 # 等同于 x = x * 4
print(x) # 24
x /= 3 # 等同于 x = x / 3
print(x) # 8.0
4. 控制流
4.1 条件语句
# if 语句
age = 18
if age >= 18:
print("你是成年人")
else:
print("你是未成年人")
# elif 语句
score = 85
if score >= 90:
print("优秀")
elif score >= 80:
print("良好")
elif score >= 60:
print("及格")
else:
print("不及格")
4.2 循环语句
while 循环
# while 循环
count = 0
while count < 5:
print(count)
count += 1
# 输出: 0 1 2 3 4
# break 和 continue
num = 0
while num < 10:
num += 1
if num % 2 == 0:
continue # 跳过偶数
if num > 7:
break # 当num大于7时退出循环
print(num)
# 输出: 1 3 5 7
for 循环
# for 循环
for i in range(5): # range(5) 生成0-4的序列
print(i)
# 输出: 0 1 2 3 4
# 遍历列表
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
# 输出: apple banana cherry
# 带索引的遍历
for index, fruit in enumerate(fruits):
print(index, fruit)
# 输出: 0 apple 1 banana 2 cherry
5. 数据结构
5.1 列表 (List)
# 创建列表
numbers = [1, 2, 3, 4, 5]
fruits = ["apple", "banana", "cherry"]
mixed = [1, "hello", 3.14, True]
# 访问元素
print(numbers[0]) # 1 (第一个元素)
print(fruits[-1]) # "cherry" (最后一个元素)
# 切片操作
print(numbers[1:3]) # [2, 3] (索引1到2的元素)
print(numbers[:3]) # [1, 2, 3] (前三个元素)
print(numbers[2:]) # [3, 4, 5] (从索引2开始的所有元素)
# 修改列表
fruits[1] = "blueberry" # 修改元素
fruits.append("orange") # 添加元素
fruits.insert(1, "mango") # 在指定位置插入元素
fruits.remove("apple") # 删除元素
popped = fruits.pop() # 移除并返回最后一个元素
# 列表操作
combined = numbers + fruits # 列表拼接
repeated = numbers * 2 # 列表重复
# 列表方法
length = len(numbers) # 获取长度
numbers.sort() # 排序
numbers.reverse() # 反转
index = fruits.index("mango") # 查找索引
5.2 元组 (Tuple)
# 创建元组
coordinates = (10, 20)
colors = ("red", "green", "blue")
single_element = (5,) # 注意逗号,表示是元组而不是括号表达式
# 访问元素
print(coordinates[0]) # 10
print(colors[-1]) # "blue"
# 元组是不可变的
# colors[1] = "yellow" # 会报错
# 元组解包
x, y = coordinates
print(x, y) # 10 20
5.3 字典 (Dictionary)
# 创建字典
person = {
"name": "Alice",
"age": 25,
"city": "New York"
}
# 访问元素
print(person["name"]) # "Alice"
print(person.get("age")) # 25
# 修改字典
person["age"] = 26 # 更新值
person["job"] = "Engineer" # 添加新键值对
# 字典方法
keys = person.keys() # 获取所有键
values = person.values() # 获取所有值
items = person.items() # 获取所有键值对
# 遍历字典
for key, value in person.items():
print(f"{key}: {value}")
5.4 集合 (Set)
# 创建集合
fruits = {"apple", "banana", "cherry"}
numbers = set([1, 2, 3, 4, 5])
# 集合操作
fruits.add("orange") # 添加元素
fruits.remove("banana") # 移除元素
fruits.discard("grape") # 安全移除元素(如果存在)
# 集合运算
a = {1, 2, 3}
b = {3, 4, 5}
print(a | b) # 并集 {1, 2, 3, 4, 5}
print(a & b) # 交集 {3}
print(a - b) # 差集 {1, 2}
print(a ^ b) # 对称差集 {1, 2, 4, 5}
6. 函数
6.1 定义函数
# 简单函数
def greet():
print("Hello!")
greet() # 输出: Hello!
# 带参数的函数
def greet_name(name):
print(f"Hello, {name}!")
greet_name("Alice") # 输出: Hello, Alice!
# 带返回值的函数
def add(a, b):
return a + b
result = add(3, 5)
print(result) # 8
# 默认参数
def power(base, exponent=2):
return base ** exponent
print(power(3)) # 9 (使用默认指数2)
print(power(3, 3)) # 27
# 可变参数
def sum_all(*numbers):
total = 0
for num in numbers:
total += num
return total
print(sum_all(1, 2, 3)) # 6
print(sum_all(1, 2, 3, 4, 5)) # 15
# 关键字参数
def person_info(**info):
for key, value in info.items():
print(f"{key}: {value}")
person_info(name="Alice", age=25, city="New York")
# 输出:
# name: Alice
# age: 25
# city: New York
6.2 Lambda 函数
# 简单的lambda函数
square = lambda x: x ** 2
print(square(5)) # 25
# 在排序中使用
pairs = [(1, 'one'), (2, 'two'), (3, 'three'), (4, 'four')]
pairs.sort(key=lambda pair: pair[1])
print(pairs) # 按第二个元素排序: [(4, 'four'), (1, 'one'), (3, 'three'), (2, 'two')]
7. 文件操作
7.1 读写文件
# 写入文件
with open("example.txt", "w") as file:
file.write("Hello, World!\n")
file.write("This is a sample file.\n")
# 读取文件
with open("example.txt", "r") as file:
content = file.read()
print(content)
# 输出:
# Hello, World!
# This is a sample file.
# 逐行读取
with open("example.txt", "r") as file:
for line in file:
print(line.strip()) # strip() 移除行尾的换行符
# 追加模式
with open("example.txt", "a") as file:
file.write("Adding a new line.\n")
8. 异常处理
# 基本异常处理
try:
result = 10 / 0
except ZeroDivisionError:
print("不能除以零!")
else:
print("结果是:", result)
finally:
print("这段代码总是会执行")
# 处理多个异常
try:
num = int(input("请输入一个数字: "))
result = 100 / num
except ValueError:
print("请输入有效的数字!")
except ZeroDivisionError:
print("不能输入零!")
else:
print(f"结果是: {result}")
# 抛出异常
def check_age(age):
if age < 0:
raise ValueError("年龄不能为负数")
if age < 18:
print("未成年人")
else:
print("成年人")
try:
check_age(-5)
except ValueError as e:
print(e) # 输出: 年龄不能为负数
9. 面向对象编程
9.1 类和对象
# 定义一个类
class Dog:
# 类属性
species = "Canis familiaris"
# 初始化方法 (构造函数)
def __init__(self, name, age):
self.name = name # 实例属性
self.age = age
# 实例方法
def description(self):
return f"{self.name} is {self.age} years old"
def speak(self, sound):
return f"{self.name} says {sound}"
# 创建实例
dog1 = Dog("Buddy", 5)
dog2 = Dog("Molly", 3)
# 访问属性和方法
print(dog1.name) # Buddy
print(dog2.age) # 3
print(dog1.description()) # Buddy is 5 years old
print(dog2.speak("Woof Woof")) # Molly says Woof Woof
9.2 继承
# 父类
class Animal:
def __init__(self, name):
self.name = name
def speak(self):
raise NotImplementedError("子类必须实现这个方法")
# 子类
class Cat(Animal):
def speak(self):
return f"{self.name} says Meow!"
class Cow(Animal):
def speak(self):
return f"{self.name} says Moo!"
# 使用子类
cat = Cat("Whiskers")
cow = Cow("Bessie")
print(cat.speak()) # Whiskers says Meow!
print(cow.speak()) # Bessie says Moo!
10. 模块和包
10.1 使用模块
# 假设有一个名为 mymodule.py 的文件,内容如下:
"""
def greet(name):
print(f"Hello, {name}!")
def add(a, b):
return a + b
"""
# 导入整个模块
import mymodule
mymodule.greet("Alice") # 输出: Hello, Alice!
print(mymodule.add(2, 3)) # 5
# 导入特定函数
from mymodule import greet, add
greet("Bob") # 输出: Hello, Bob!
print(add(5, 7)) # 12
# 导入并重命名
from mymodule import greet as hello
hello("Charlie") # 输出: Hello, Charlie!
# 导入所有内容 (不推荐)
from mymodule import *
greet("Dave") # 输出: Hello, Dave!
10.2 创建包
my_package/
__init__.py
module1.py
module2.py
subpackage/
__init__.py
module3.py
# 使用包
from my_package import module1
from my_package.subpackage import module3
11. 常用内置函数
# abs() - 绝对值
print(abs(-5)) # 5
# len() - 长度
print(len("hello")) # 5
print(len([1, 2, 3])) # 3
# max() / min() - 最大值/最小值
print(max(1, 5, 3)) # 5
print(min([10, 2, 8])) # 2
# sum() - 求和
print(sum([1, 2, 3, 4])) # 10
# sorted() - 排序
numbers = [3, 1, 4, 1, 5, 9, 2]
print(sorted(numbers)) # [1, 1, 2, 3, 4, 5, 9]
# enumerate() - 枚举
fruits = ['apple', 'banana', 'cherry']
for index, fruit in enumerate(fruits):
print(index, fruit)
# 输出:
# 0 apple
# 1 banana
# 2 cherry
# zip() - 并行迭代
names = ['Alice', 'Bob', 'Charlie']
ages = [25, 30, 35]
for name, age in zip(names, ages):
print(f"{name} is {age} years old")
# 输出:
# Alice is 25 years old
# Bob is 30 years old
# Charlie is 35 years old
12. 列表推导式和生成器表达式
12.1 列表推导式
# 简单的列表推导式
squares = [x**2 for x in range(10)]
print(squares) # [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
# 带条件的列表推导式
even_squares = [x**2 for x in range(10) if x % 2 == 0]
print(even_squares) # [0, 4, 16, 36, 64]
# 嵌套的列表推导式
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
flattened = [num for row in matrix for num in row]
print(flattened) # [1, 2, 3, 4, 5, 6, 7, 8, 9]
12.2 生成器表达式
# 生成器表达式 (惰性求值)
squares_gen = (x**2 for x in range(10))
print(squares_gen) # <generator object <genexpr> at 0x...>
print(list(squares_gen)) # [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
# 生成器表达式在函数中使用
sum_of_squares = sum(x**2 for x in range(10))
print(sum_of_squares) # 285
13. 装饰器
# 简单的装饰器
def my_decorator(func):
def wrapper():
print("函数执行前...")
func()
print("函数执行后...")
return wrapper
@my_decorator
def say_hello():
print("Hello!")
say_hello()
# 输出:
# 函数执行前...
# Hello!
# 函数执行后...
# 带参数的装饰器
def repeat(num_times):
def decorator(func):
def wrapper(*args, **kwargs):
for _ in range(num_times):
result = func(*args, **kwargs)
return result
return wrapper
return decorator
@repeat(num_times=3)
def greet(name):
print(f"Hello, {name}!")
greet("Alice")
# 输出:
# Hello, Alice!
# Hello, Alice!
# Hello, Alice!
14. 上下文管理器
# 使用 with 语句
with open('example.txt', 'r') as file:
content = file.read()
print(content)
# 文件会在with块结束后自动关闭
# 自定义上下文管理器
class ManagedFile:
def __init__(self, filename, mode):
self.filename = filename
self.mode = mode
def __enter__(self):
self.file = open(self.filename, self.mode)
return self.file
def __exit__(self, exc_type, exc_val, exc_tb):
if self.file:
self.file.close()
with ManagedFile('example.txt', 'r') as f:
content = f.read()
print(content)
15. 虚拟环境和包管理
虽然这不是语法部分,但对Python开发至关重要:
# 创建虚拟环境
python -m venv myenv
# 激活虚拟环境 (Windows)
myenv\Scripts\activate
# 激活虚拟环境 (macOS/Linux)
source myenv/bin/activate
# 安装包
pip install requests numpy pandas
# 列出已安装的包
pip list
# 生成requirements.txt
pip freeze > requirements.txt
# 从requirements.txt安装
pip install -r requirements.txt
结语
本文涵盖了 Python 的基础语法和核心概念,包括变量、数据类型、运算符、控制流、函数、面向对象编程等。掌握这些基础知识后,你就可以开始编写功能完善的 Python 程序了。Python 的强大之处还在于其丰富的标准库和第三方库,建议在实际项目中不断练习和探索。