第二单元:Python核心语法与数据结构

约2周学习时间,掌握Python的核心语法和常用数据结构

2.1 变量与数据类型

Python中的变量是用来存储数据的容器,不需要声明类型,直接赋值即可。

基本数据类型

数值类型

  • 整数 (int): 如 1, 2, 3
  • 浮点数 (float): 如 1.5, 2.0, 3.14
  • 复数 (complex): 如 1+2j

文本类型

  • 字符串 (str): 如 "Hello", 'Python'

布尔类型

  • 布尔值 (bool): True, False

空值

  • None: 表示空值

变量赋值示例

# 变量赋值
name = "Alice"
age = 25
height = 1.65
is_student = True

# 多变量赋值
a, b, c = 1, 2, 3

# 输出变量
print(name, age, height, is_student)
print(a, b, c)

2.2 运算符

算术运算符

  • +: 加法
  • -: 减法
  • *: 乘法
  • /: 除法
  • //: 整除
  • %: 取模
  • **: 幂运算

比较运算符

  • ==: 等于
  • !=: 不等于
  • >: 大于
  • <: 小于
  • >=: 大于等于
  • <=: 小于等于

逻辑运算符

  • and: 与
  • or: 或
  • not: 非

赋值运算符

  • =: 赋值
  • +=: 加赋值
  • -=: 减赋值
  • *=: 乘赋值
  • /=: 除赋值

运算符示例

# 算术运算符示例
a = 10
b = 3
print("a + b =", a + b) # 13
print("a - b =", a - b) # 7
print("a * b =", a * b) # 30
print("a / b =", a / b) # 3.333...
print("a // b =", a // b) # 3
print("a % b =", a % b) # 1
print("a ** b =", a ** b) # 1000

# 逻辑运算符示例
x = True
y = False
print("x and y =", x and y) # False
print("x or y =", x or y) # True
print("not x =", not x) # False

2.3 控制流语句

条件语句 (if-elif-else)

# 条件语句示例
score = 85

if score >= 90:     print("优秀") elif score >= 80:     print("良好") elif score >= 60:     print("及格") else:     print("不及格")

循环语句

for循环

# for循环示例
for i in range(5):     print(i)

# 遍历列表
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:     print(fruit)

while循环

# while循环示例
count = 0
while count < 5:     print(count)     count += 1
# 无限循环
# while True:
# print("无限循环")

循环控制语句

# break语句示例
for i in range(10):     if i == 5:         break # 跳出循环     print(i)

# continue语句示例
for i in range(10):     if i % 2 == 0:         continue # 跳过当前循环     print(i)

2.4 数据结构

列表 (List)

有序、可变的元素集合

# 列表创建与操作
fruits = ["apple", "banana", "cherry"]
print(fruits[0]) # 访问元素
fruits.append("orange") # 添加元素
fruits.remove("banana") # 删除元素
print(fruits) # 输出列表

元组 (Tuple)

有序、不可变的元素集合

# 元组创建与操作
colors = ("red", "green", "blue")
print(colors[1]) # 访问元素
# colors[0] = "yellow" # 错误:元组不可变
print(colors) # 输出元组

字典 (Dictionary)

无序的键值对集合

# 字典创建与操作
person = {     "name": "Alice",     "age": 25,     "city": "New York" }
print(person["name"]) # 访问值
person["age"] = 26 # 修改值
person["country"] = "USA" # 添加键值对
print(person) # 输出字典

集合 (Set)

无序、无重复元素的集合

# 集合创建与操作
numbers = {1, 2, 3, 3, 4}
print(numbers) # 自动去重
numbers.add(5) # 添加元素
numbers.remove(2) # 删除元素
print(numbers) # 输出集合

数据结构操作示例

# 列表推导式
squares = [x**2 for x in range(10)]
print(squares) # [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

# 字典推导式
square_dict = {x: x**2 for x in range(5)}
print(square_dict) # {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}

# 集合操作
set1 = {1, 2, 3}
set2 = {3, 4, 5}
print(set1 | set2) # 并集 {1, 2, 3, 4, 5}
print(set1 & set2) # 交集 {3}
print(set1 - set2) # 差集 {1, 2}

2.5 字符串操作

Python中的字符串是不可变的,支持多种操作和方法。

字符串基本操作

# 字符串创建
s1 = "Hello"
s2 = 'World'
s3 = """多行 字符串"""
# 字符串拼接
s = s1 + " " + s2
print(s) # Hello World

# 字符串重复
print("A" * 5) # AAAAA

# 字符串切片
print(s[0:5]) # Hello
print(s[6:]) # World

字符串方法

# 字符串方法
s = "Hello, Python!"
print(s.lower()) # 转换为小写
print(s.upper()) # 转换为大写
print(s.strip()) # 去除首尾空白
print(s.split(",")) # 分割字符串
print(s.replace("Python", "World")) # 替换字符串
print("Python" in s) # 检查子串

字符串格式化

# 字符串格式化
name = "Alice"
age = 25

# 方法1: 占位符
print("My name is %s and I am %d years old." % (name, age))

# 方法2: format方法
print("My name is {} and I am {} years old.".format(name, age))

# 方法3: f-string (Python 3.6+)
print(f"My name is {name} and I am {age} years old.")

单元小结

通过本单元的学习,你已经掌握了Python的核心语法和常用数据结构,包括变量、运算符、控制流语句、列表、字典、元组和集合等。这些是Python编程的基础,也是后续学习的重要基石。

Python 代码运行器

运行结果:

点击"运行代码"查看结果...