Python 基础语法教程:从零开始学 Python
17 min read
#Python#编程基础#入门教程#语法
Python 基础语法教程:从零开始学 Python
Python 是一种高级、解释型、通用的编程语言,以其简洁易读的语法和强大的功能而闻名。本教程将带你系统学习 Python 的基础语法。
为什么学习 Python?
- 简单易学:语法简洁清晰,接近自然语言
- 应用广泛:Web 开发、数据分析、人工智能、自动化等
- 强大的生态:丰富的第三方库和框架
- 跨平台:支持 Windows、macOS、Linux
- 社区活跃:庞大的开发者社区,资源丰富
环境准备
安装 Python
访问 Python 官网 下载最新版本(推荐 Python 3.10+)。
# 检查 Python 版本
python --version
# 或
python3 --version
第一个 Python 程序
创建 hello.py 文件:
print("Hello, World!")
运行程序:
python hello.py
基础语法
1. 注释
# 这是单行注释
"""
这是多行注释
可以跨越多行
"""
'''
这也是多行注释
使用单引号
'''
2. 变量和赋值
Python 是动态类型语言,不需要声明变量类型:
# 基本赋值
name = "Alice"
age = 25
height = 1.68
is_student = True
# 多重赋值
x, y, z = 1, 2, 3
# 链式赋值
a = b = c = 0
# 交换变量
x, y = y, x
# 变量命名规则
# ✅ 正确:使用字母、数字、下划线,不能以数字开头
user_name = "John"
user1 = "Jane"
_private = "secret"
# ❌ 错误:不能使用关键字和特殊字符
# class = "A" # class 是关键字
# user-name = "John" # 不能使用连字符
3. 数据类型
数字类型
# 整数 (int)
x = 10
y = -5
big_num = 1_000_000 # 使用下划线提高可读性
# 浮点数 (float)
pi = 3.14159
scientific = 1.5e-3 # 科学计数法:0.0015
# 复数 (complex)
z = 3 + 4j
print(z.real) # 3.0
print(z.imag) # 4.0
# 类型转换
num_str = "123"
num_int = int(num_str) # 字符串转整数
num_float = float(num_str) # 字符串转浮点数
字符串 (str)
# 字符串定义
single = 'Hello'
double = "World"
multi_line = """这是
多行
字符串"""
# 字符串操作
text = "Python Programming"
# 索引和切片
print(text[0]) # 'P' - 第一个字符
print(text[-1]) # 'g' - 最后一个字符
print(text[0:6]) # 'Python' - 切片 [start:end]
print(text[7:]) # 'Programming' - 从索引7到结尾
print(text[:6]) # 'Python' - 从开始到索引6
print(text[::2]) # 'Pto rgamn' - 步长为2
# 字符串方法
print(text.lower()) # 转小写
print(text.upper()) # 转大写
print(text.replace('P', 'J')) # 替换
print(text.split()) # 分割成列表
print(text.startswith('Py')) # True - 检查开头
print(text.endswith('ing')) # True - 检查结尾
print(text.find('Pro')) # 7 - 查找子串位置
print(len(text)) # 18 - 字符串长度
# 字符串格式化
name = "Alice"
age = 25
# f-string (推荐,Python 3.6+)
message = f"My name is {name}, I'm {age} years old"
# format 方法
message = "My name is {}, I'm {} years old".format(name, age)
message = "My name is {n}, I'm {a} years old".format(n=name, a=age)
# % 格式化(旧式)
message = "My name is %s, I'm %d years old" % (name, age)
布尔类型 (bool)
# 布尔值
is_active = True
is_deleted = False
# 布尔运算
print(True and False) # False
print(True or False) # True
print(not True) # False
# 比较运算返回布尔值
print(5 > 3) # True
print(5 == 5) # True
print(5 != 3) # True
# 真值测试
# 以下值被视为 False:
# False, None, 0, 0.0, '', [], {}, ()
print(bool(0)) # False
print(bool("")) # False
print(bool([])) # False
print(bool("text")) # True
4. 数据结构
列表 (List)
列表是可变的有序集合:
# 创建列表
fruits = ["apple", "banana", "cherry"]
numbers = [1, 2, 3, 4, 5]
mixed = [1, "hello", 3.14, True]
empty = []
# 访问元素
print(fruits[0]) # 'apple'
print(fruits[-1]) # 'cherry' - 最后一个元素
# 切片
print(numbers[1:4]) # [2, 3, 4]
print(numbers[:3]) # [1, 2, 3]
print(numbers[2:]) # [3, 4, 5]
# 修改列表
fruits[0] = "orange" # 修改元素
fruits.append("grape") # 添加到末尾
fruits.insert(1, "kiwi") # 在指定位置插入
fruits.extend(["mango", "pear"]) # 扩展列表
fruits.remove("banana") # 删除指定元素
popped = fruits.pop() # 删除并返回最后一个元素
popped = fruits.pop(0) # 删除并返回指定位置元素
# 列表操作
print(len(fruits)) # 列表长度
print("apple" in fruits) # 检查元素是否存在
fruits.sort() # 排序
fruits.reverse() # 反转
fruits.clear() # 清空列表
# 列表推导式
squares = [x**2 for x in range(10)] # [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
evens = [x for x in range(20) if x % 2 == 0] # [0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
元组 (Tuple)
元组是不可变的有序集合:
# 创建元组
point = (3, 4)
colors = ("red", "green", "blue")
single = (1,) # 单元素元组需要逗号
empty = ()
# 访问元素
print(point[0]) # 3
print(colors[-1]) # 'blue'
# 元组解包
x, y = point
r, g, b = colors
# 元组不可修改
# point[0] = 5 # TypeError: 'tuple' object does not support item assignment
# 元组操作
print(len(colors)) # 3
print("red" in colors) # True
字典 (Dictionary)
字典是键值对的集合:
# 创建字典
person = {
"name": "Alice",
"age": 25,
"city": "Beijing"
}
# 访问元素
print(person["name"]) # 'Alice'
print(person.get("age")) # 25
print(person.get("email", "N/A")) # 'N/A' - 提供默认值
# 修改字典
person["age"] = 26 # 修改值
person["email"] = "alice@example.com" # 添加新键值对
del person["city"] # 删除键值对
removed = person.pop("email") # 删除并返回值
# 字典操作
print(len(person)) # 字典大小
print("name" in person) # 检查键是否存在
print(person.keys()) # 获取所有键
print(person.values()) # 获取所有值
print(person.items()) # 获取所有键值对
# 遍历字典
for key in person:
print(key, person[key])
for key, value in person.items():
print(f"{key}: {value}")
# 字典推导式
squares_dict = {x: x**2 for x in range(5)} # {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}
集合 (Set)
集合是无序的不重复元素集:
# 创建集合
fruits = {"apple", "banana", "cherry"}
numbers = set([1, 2, 3, 3, 4]) # {1, 2, 3, 4} - 自动去重
empty = set() # 空集合
# 集合操作
fruits.add("orange") # 添加元素
fruits.remove("banana") # 删除元素(不存在会报错)
fruits.discard("grape") # 删除元素(不存在不报错)
# 集合运算
a = {1, 2, 3, 4}
b = {3, 4, 5, 6}
print(a | b) # {1, 2, 3, 4, 5, 6} - 并集
print(a & b) # {3, 4} - 交集
print(a - b) # {1, 2} - 差集
print(a ^ b) # {1, 2, 5, 6} - 对称差集
5. 运算符
算术运算符
x = 10
y = 3
print(x + y) # 13 - 加法
print(x - y) # 7 - 减法
print(x * y) # 30 - 乘法
print(x / y) # 3.333... - 除法
print(x // y) # 3 - 整除
print(x % y) # 1 - 取模
print(x ** y) # 1000 - 幂运算
比较运算符
print(5 == 5) # True - 等于
print(5 != 3) # True - 不等于
print(5 > 3) # True - 大于
print(5 < 3) # False - 小于
print(5 >= 5) # True - 大于等于
print(5 <= 3) # False - 小于等于
逻辑运算符
print(True and False) # False - 与
print(True or False) # True - 或
print(not True) # False - 非
赋值运算符
x = 5
x += 3 # x = x + 3
x -= 2 # x = x - 2
x *= 4 # x = x * 4
x /= 2 # x = x / 2
x //= 3 # x = x // 3
x %= 2 # x = x % 2
x **= 2 # x = x ** 2
6. 控制流
if 语句
# 基本 if 语句
age = 18
if age >= 18:
print("成年人")
# if-else 语句
if age >= 18:
print("成年人")
else:
print("未成年人")
# if-elif-else 语句
score = 85
if score >= 90:
grade = "A"
elif score >= 80:
grade = "B"
elif score >= 70:
grade = "C"
elif score >= 60:
grade = "D"
else:
grade = "F"
print(f"成绩等级: {grade}")
# 三元运算符
status = "成年人" if age >= 18 else "未成年人"
for 循环
# 遍历列表
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
# 遍历字符串
for char in "Python":
print(char)
# 使用 range()
for i in range(5): # 0, 1, 2, 3, 4
print(i)
for i in range(1, 6): # 1, 2, 3, 4, 5
print(i)
for i in range(0, 10, 2): # 0, 2, 4, 6, 8
print(i)
# enumerate() - 获取索引和值
for index, fruit in enumerate(fruits):
print(f"{index}: {fruit}")
# zip() - 并行遍历多个序列
names = ["Alice", "Bob", "Charlie"]
ages = [25, 30, 35]
for name, age in zip(names, ages):
print(f"{name} is {age} years old")
while 循环
# 基本 while 循环
count = 0
while count < 5:
print(count)
count += 1
# 无限循环(需要 break 退出)
while True:
user_input = input("输入 'quit' 退出: ")
if user_input == "quit":
break
print(f"你输入了: {user_input}")
break 和 continue
# break - 跳出循环
for i in range(10):
if i == 5:
break
print(i) # 输出 0, 1, 2, 3, 4
# continue - 跳过当前迭代
for i in range(10):
if i % 2 == 0:
continue
print(i) # 输出 1, 3, 5, 7, 9
# else 子句(循环正常结束时执行)
for i in range(5):
print(i)
else:
print("循环正常结束")
7. 函数
定义和调用函数
# 基本函数
def greet():
print("Hello, World!")
greet() # 调用函数
# 带参数的函数
def greet_person(name):
print(f"Hello, {name}!")
greet_person("Alice")
# 带返回值的函数
def add(a, b):
return a + b
result = add(3, 5)
print(result) # 8
# 多个返回值
def get_user_info():
name = "Alice"
age = 25
return name, age
name, age = get_user_info()
参数类型
# 默认参数
def greet(name, greeting="Hello"):
print(f"{greeting}, {name}!")
greet("Alice") # Hello, Alice!
greet("Bob", "Hi") # Hi, Bob!
# 关键字参数
def describe_person(name, age, city):
print(f"{name} is {age} years old and lives in {city}")
describe_person(name="Alice", age=25, city="Beijing")
describe_person(age=30, city="Shanghai", name="Bob")
# 可变参数 (*args)
def sum_all(*numbers):
return sum(numbers)
print(sum_all(1, 2, 3)) # 6
print(sum_all(1, 2, 3, 4, 5)) # 15
# 关键字可变参数 (**kwargs)
def print_info(**info):
for key, value in info.items():
print(f"{key}: {value}")
print_info(name="Alice", age=25, city="Beijing")
Lambda 函数
# 匿名函数
square = lambda x: x ** 2
print(square(5)) # 25
add = lambda a, b: a + b
print(add(3, 5)) # 8
# 在高阶函数中使用
numbers = [1, 2, 3, 4, 5]
squared = list(map(lambda x: x ** 2, numbers))
print(squared) # [1, 4, 9, 16, 25]
evens = list(filter(lambda x: x % 2 == 0, numbers))
print(evens) # [2, 4]
8. 面向对象编程
类和对象
# 定义类
class Person:
# 类变量
species = "Homo sapiens"
# 构造函数
def __init__(self, name, age):
# 实例变量
self.name = name
self.age = age
# 实例方法
def greet(self):
print(f"Hello, my name is {self.name}")
def have_birthday(self):
self.age += 1
print(f"Happy birthday! Now I'm {self.age} years old")
# 类方法
@classmethod
def get_species(cls):
return cls.species
# 静态方法
@staticmethod
def is_adult(age):
return age >= 18
# 创建对象
person1 = Person("Alice", 25)
person2 = Person("Bob", 30)
# 调用方法
person1.greet() # Hello, my name is Alice
person1.have_birthday() # Happy birthday! Now I'm 26 years old
# 访问属性
print(person1.name) # Alice
print(person1.age) # 26
# 调用类方法和静态方法
print(Person.get_species()) # Homo sapiens
print(Person.is_adult(20)) # True
继承
# 父类
class Animal:
def __init__(self, name):
self.name = name
def speak(self):
pass
# 子类
class Dog(Animal):
def speak(self):
return f"{self.name} says Woof!"
class Cat(Animal):
def speak(self):
return f"{self.name} says Meow!"
# 使用继承
dog = Dog("Buddy")
cat = Cat("Whiskers")
print(dog.speak()) # Buddy says Woof!
print(cat.speak()) # Whiskers says Meow!
9. 异常处理
# 基本异常处理
try:
result = 10 / 0
except ZeroDivisionError:
print("不能除以零!")
# 捕获多个异常
try:
number = int(input("输入一个数字: "))
result = 10 / number
except ValueError:
print("无效的输入!")
except ZeroDivisionError:
print("不能除以零!")
# 捕获所有异常
try:
# 可能出错的代码
risky_operation()
except Exception as e:
print(f"发生错误: {e}")
# else 和 finally
try:
file = open("data.txt", "r")
content = file.read()
except FileNotFoundError:
print("文件不存在")
else:
print("文件读取成功")
finally:
print("清理资源")
# file.close()
# 抛出异常
def validate_age(age):
if age < 0:
raise ValueError("年龄不能为负数")
if age > 150:
raise ValueError("年龄不合理")
return True
try:
validate_age(-5)
except ValueError as e:
print(e)
10. 文件操作
# 写入文件
with open("output.txt", "w", encoding="utf-8") as file:
file.write("Hello, World!\n")
file.write("Python is awesome!")
# 读取文件
with open("output.txt", "r", encoding="utf-8") as file:
content = file.read()
print(content)
# 逐行读取
with open("output.txt", "r", encoding="utf-8") as file:
for line in file:
print(line.strip())
# 追加内容
with open("output.txt", "a", encoding="utf-8") as file:
file.write("\nNew line added")
# 读取所有行到列表
with open("output.txt", "r", encoding="utf-8") as file:
lines = file.readlines()
print(lines)
11. 模块和包
# 导入标准库模块
import math
print(math.pi) # 3.141592653589793
print(math.sqrt(16)) # 4.0
# 导入特定函数
from math import pi, sqrt
print(pi)
print(sqrt(16))
# 使用别名
import math as m
print(m.pi)
from math import sqrt as square_root
print(square_root(16))
# 导入所有(不推荐)
from math import *
# 导入自定义模块
# 假设有 mymodule.py 文件
# import mymodule
# mymodule.my_function()
实战练习
练习 1:计算器
def calculator():
print("简单计算器")
print("1. 加法")
print("2. 减法")
print("3. 乘法")
print("4. 除法")
choice = input("选择操作 (1/2/3/4): ")
num1 = float(input("输入第一个数字: "))
num2 = float(input("输入第二个数字: "))
if choice == '1':
print(f"{num1} + {num2} = {num1 + num2}")
elif choice == '2':
print(f"{num1} - {num2} = {num1 - num2}")
elif choice == '3':
print(f"{num1} * {num2} = {num1 * num2}")
elif choice == '4':
if num2 != 0:
print(f"{num1} / {num2} = {num1 / num2}")
else:
print("错误:不能除以零")
else:
print("无效的选择")
calculator()
练习 2:学生成绩管理
class Student:
def __init__(self, name, student_id):
self.name = name
self.student_id = student_id
self.grades = {}
def add_grade(self, subject, grade):
self.grades[subject] = grade
def get_average(self):
if not self.grades:
return 0
return sum(self.grades.values()) / len(self.grades)
def display_info(self):
print(f"学生姓名: {self.name}")
print(f"学号: {self.student_id}")
print("成绩:")
for subject, grade in self.grades.items():
print(f" {subject}: {grade}")
print(f"平均分: {self.get_average():.2f}")
# 使用示例
student = Student("张三", "2024001")
student.add_grade("数学", 95)
student.add_grade("英语", 88)
student.add_grade("物理", 92)
student.display_info()
最佳实践
- 遵循 PEP 8 代码风格指南
- 使用有意义的变量名
- 编写文档字符串(docstrings)
- 避免全局变量
- 使用列表推导式简化代码
- 使用 with 语句管理资源
- 适当使用异常处理
- 编写可测试的代码
下一步学习
- 高级特性:装饰器、生成器、上下文管理器
- 标准库:os, sys, datetime, json, re 等
- 第三方库:requests, numpy, pandas, matplotlib
- Web 开发:Flask, Django, FastAPI
- 数据科学:NumPy, Pandas, Matplotlib, Scikit-learn
总结
通过本教程,你已经掌握了 Python 的核心基础知识:
- ✅ 变量和数据类型
- ✅ 数据结构(列表、元组、字典、集合)
- ✅ 控制流(if、for、while)
- ✅ 函数定义和使用
- ✅ 面向对象编程
- ✅ 异常处理
- ✅ 文件操作
- ✅ 模块导入
继续实践和探索,你将能够使用 Python 解决各种实际问题!