📚 Python 编程基础
点击卡片按钮,探索更多内容
Module 0: Python Ultra Basic Syntax
Learning Objectives: From zero to mastering the most basic Python syntax needed to read and write code. No programming background required.
学习目标:从零开始,掌握阅读和编写 Python 代码所需的最基础语法。不需要任何编程基础。
1. What is Python?
Python is a programming language that you can use to: write small games, process data, control website backends, and automate tasks. The goal of learning Python is to understand the basic concepts of programming, not to become an expert.
Python是一种编程语言,你可以用它来:写小游戏、处理数据、控制网站后台、做自动化任务。我们学习Python的目的是理解编程的基本概念,而不是成为专家。
2. First Program: Print Output
2. 第一个程序:打印输出
print("Hello World!")
Output / 输出:
Hello World!
| Part | Meaning / 含义 |
|---|---|
print |
Function name for printing / 打印函数的名字 |
( |
Start passing arguments / 开始传参数 |
"Hello World!" |
Content to print (string) / 要打印的内容(字符串) |
) |
End / 结束 |
| Whole line | Tells Python to execute the “print” action / 告诉Python执行「打印」这个动作 |
More examples / 更多例子:
print(123) # Print number / 打印数字
print(3 + 5) # Print calculation result (8) / 打印计算结果(8)
print("3 + 5") # Print text, no calculation / 打印文字,不会计算
Output / 输出:
123 8 3 + 5
Try it yourself / 自己试一试:
print("My name is XXX")
print(100 - 25)
3. Variables: Naming Data
3. 变量:给数据起名字
First variable / 第一个变量:
name = "Haoran" print(name)
Output: Haoran
| Code / 代码 | Meaning / 含义 |
|---|---|
name |
Variable name / 变量名 |
= |
Assignment operator (puts right value into left box) / 赋值符号(把右边的值放到左边的盒子里) |
"Haoran" |
Value (a string) / 值(一个字符串) |
Variable values can change / 变量的值可以改变:
score = 0 print(score) # Output: 0 score = 10 print(score) # Output: 10 score = score + 5 print(score) # Output: 15
Key understanding: score = score + 5 means: first calculate the right side (10 + 5 = 15), then put 15 back into the variable score.
重点理解:score = score + 5 的意思是:先计算右边的 score + 5(10 + 5 = 15),然后把 15 放回 score 这个盒子里。
4. Variable Naming Rules
4. 变量的命名规则
| Rule | Correct Example | Wrong Example |
|---|---|---|
| Letters, numbers, underscores only | player1, my_score |
player-1 (hyphen not allowed) |
| Cannot start with a number | score_1 |
1_score |
| Case-sensitive | Score and score are different |
– |
| Cannot be Python keywords | player_name |
if, for, print |
Good habits / 命名的好习惯:
# Bad (hard to understand) / 不好(看不懂) a = 10 b = 20 c = a + b # Good (clear purpose) / 好(一目了然) player_energy = 10 monster_damage = 3 remaining_energy = player_energy - monster_damage
Principle: Variable names should clearly indicate their purpose.
原则:变量名要让人一看就懂它的用途。
5. Data Types
5. 数据类型
1. Integer (int) / 整数
age = 20 steps = 100 energy = 10
2. Float — decimal numbers / 浮点数(小数)
price = 19.99 percentage = 75.5 pi = 3.14159
3. String (str) — text / 字符串(文本)
name = "Haoran" animal = "Lion" message = "Hello World!" # Both are correct / 都正确 name1 = "Haoran" name2 = 'Haoran'
4. Boolean (bool) — True or False / 布尔值(真或假)
is_alive = True is_game_over = False has_key = True
Use type() to check data types / 用 type() 查看数据类型:
print(type(10)) # <class 'int'>
print(type(3.14)) # <class 'float'>
print(type("Hi")) # <class 'str'>
print(type(True)) # <class 'bool'>
6. Arithmetic Operators
6. 算术运算符
| Operator | Meaning | Example | Result |
|---|---|---|---|
+ |
Addition / 加法 | 5 + 3 |
8 |
- |
Subtraction / 减法 | 10 - 4 |
6 |
* |
Multiplication / 乘法 | 3 * 4 |
12 |
/ |
Division / 除法 | 15 / 2 |
7.5 |
// |
Floor division / 整除 | 15 // 2 |
7 |
% |
Modulus / 取余 | 15 % 2 |
1 |
** |
Exponentiation / 幂 | 2 ** 3 |
8 |
Examples / 例子:
total_score = 100 + 50 print(total_score) # 150 half = total_score / 2 print(half) # 75.0 is_even = total_score % 2 print(is_even) # 0 (150 is even / 150是偶数) square = 5 ** 2 print(square) # 25
Augmented assignment (shorthand) / 简写运算符:
score = 10 # These three have the same effect / 以下三种写法效果相同 score = score + 5 score += 5 # Most common / 最常用 # Other shorthand / 其他简写 score -= 3 # score = score - 3 score *= 2 # score = score * 2 score /= 4 # score = score / 4
7. String Operations
7. 字符串操作
String concatenation (using +) / 字符串拼接(用 +):
first_name = "Haoran" last_name = "Jia" full_name = first_name + " " + last_name print(full_name) # Haoran Jia
String and number concatenation (need conversion) / 字符串和数字拼接(需要转换):
age = 20 # The following line will cause an error / 下面这行会报错 # message = "I am " + age + " years old" # Correct way: use str() to convert / 正确做法:用 str() 转换 message = "I am " + str(age) + " years old" print(message) # I am 20 years old
f-string (simpler way, Python 3.6+) / f-string(更简单的方式,Python 3.6+):
name = "Haoran"
age = 20
energy = 10
# f-string: add f before the string, use {variable_name} to insert variables
# f-string:在字符串前面加 f,用 {变量名} 插入变量
message = f"My name is {name}, I am {age} years old, energy is {energy}"
print(message) # My name is Haoran, I am 20 years old, energy is 10
# You can even put calculations inside / 甚至可以放计算
print(f"5 + 3 = {5 + 3}") # 5 + 3 = 8
Recommendation: Use f-string for everything, it’s the simplest.
建议:以后都用 f-string,最简单。
8. User Input
8. 输入:让用户输入信息
name = input("Please enter your name: ")
print(f"Hello, {name}!")
Output / 运行效果:
Please enter your name: Haoran Hello, Haoran!
Note: input() always returns a string. If you need a number, you must convert it.
注意:input() 返回的永远是字符串,如果是数字需要转换。
age_str = input("Please enter your age: ")
age = int(age_str) # Convert to integer / 转换成整数
# Or in one step / 或者一步完成
age = int(input("Please enter your age: "))
9. Comments
9. 注释:给代码写说明
# This is a single-line comment / 这是单行注释 """ This is a multi-line comment You can write many lines Use three double quotes 这是多行注释 可以写很多行 用三个双引号 """ # Real example / 实际例子 # Initialize player attributes / 初始化玩家属性 player_name = "Haoran" # Player name / 玩家名字 player_energy = 10 # Player energy, initial value 10 / 玩家能量,初始为 10
Good habit: Write comments for complex code, skip comments for simple code.
好习惯:复杂的地方写注释,简单的地方不用写。
10. Exercises: Put What You’ve Learned into Practice
10. 练习:把所学用起来
Exercise 1 / 练习 1: Variables & Print
Please write code to: 1. Create a variable called player_name with your name. 2. Create a variable called player_level with value 1. 3. Print “Player [name]’s level is [level]”
请写出代码完成以下任务:1. 创建一个变量叫 player_name,值为你的名字。2. 创建一个变量叫 player_level,值为 1。3. 打印 “玩家 XXX 的等级是 X”。
player_name = "Haoran"
player_level = 1
print(f"Player {player_name}'s level is {player_level}")
Exercise 2 / 练习 2: Calculation
Player starts with 100 energy. Encountering a monster loses 25 energy. Calculate and print the remaining energy.
玩家初始能量 100,遇到怪物损失 25 能量,请计算剩余能量并打印。
energy = 100
damage = 25
energy = energy - damage
print(f"Remaining energy: {energy}")
Exercise 3 / 练习 3: Input & Calculation
Ask the user for two numbers, then print their sum.
让用户输入两个数字,打印这两个数字的和。
num1 = int(input("Enter first number: "))
num2 = int(input("Enter second number: "))
sum_result = num1 + num2
print(f"{num1} + {num2} = {sum_result}")
Exercise 4 / 练习 4: Odd or Even
Ask the user for a number, use the % operator to determine if it’s odd or even. (Hint: even % 2 == 0)
让用户输入一个数字,用 % 运算符判断它是奇数还是偶数。(提示:偶数 % 2 == 0)
num = int(input("Enter a number: "))
if num % 2 == 0:
print(f"{num} is even")
else:
print(f"{num} is odd")
11. Module 0 Cheat Sheet
11. Module 0 知识点速查表
| Concept | Code Example |
|---|---|
| Print / 打印 | print("Hello") |
| Variable assignment / 变量赋值 | x = 10 |
| Variable modification / 变量修改 | x = x + 1 or x += 1 |
| Integer / 整数 | 10, -5, 0 |
| Float / 浮点数 | 3.14, 2.5 |
| String / 字符串 | "Hello", 'Hi' |
| Boolean / 布尔值 | True, False |
| Addition / 加法 | a + b |
| Subtraction / 减法 | a - b |
| Multiplication / 乘法 | a * b |
| Division / 除法 | a / b |
| Floor division / 整除 | a // b |
| Modulus / 取余 | a % b |
| String concatenation / 字符串拼接 | "A" + "B" |
| Type conversion / 类型转换 | str(20), int("20") |
| f-string | f"Value is {x}" |
| Input / 输入 | input("Prompt: ") |
| Comment / 注释 | # Comment |
✅ Module 0 Complete! You have mastered the most essential Python basic syntax. Keep going!
✅ Module 0 完成!你已经掌握了 Python 最核心的基础语法。继续加油!
Module 1: Variables & Game State
Learning Objectives: Understand how to use variables to track game state, master initial values, change rules, and learn to trace variable changes.
学习目标:理解程序中如何用变量记录游戏状态,掌握变量的初始值、变化规则,学会追踪变量的变化过程。
Prerequisite: Module 0 (variables, print, assignment, arithmetic) · Estimated time: 1.5–2 hours
前置知识:Module 0(变量、print、赋值、算术运算)· 预估时间:1.5–2小时
1. From Life to Code: What is “State”?
1. 从生活到代码:什么是「状态」?
Imagine you’re playing a board game with three counters on the table:
| Counter / 计数器 | Current Value / 当前值 | Meaning / 含义 | ||
|---|---|---|---|---|
| Steps taken / 走的步数 | 5 | 已经走了 5 步 | ||
| Health / 生命值 | 7 | 还剩 7 点生命 | ||
| Score / 分数 | 120 | 当前分数是 120 |
| Variable / 变量名 | Meaning / 含义 | Typical Initial Value / 典型初始值 | ||
|---|---|---|---|---|
steps |
Total moves made by player / 玩家总共移动了多少步 | 0 | ||
energy |
Player’s remaining energy / 玩家剩余能量 | 10 | ||
score |
Player’s current score / 玩家当前分数 | 0 |
| Variable | Initial Value | Trigger | Change Rule | |
|---|---|---|---|---|
steps |
0 | Player moves (press direction key) | +1 each time | |
energy |
10 | Hit wall or monster | -3 each time | |
score |
0 | steps or energy changes | Formula calculation |
| Scenario / 场景 | steps | current energy | Calculation / 计算过程 | score |
|---|---|---|---|---|
| Start / 刚开局 | 0 | 10 | 0 + (10-10) | 0 |
| 3 steps, no collision / 走了3步,无碰撞 | 3 | 10 | 3 + (10-10) | 3 |
| Hit wall once / 撞墙1次 | 4 | 7 | 4 + (10-7) | 7 |
| Hit monster once / 撞怪物1次 | 5 | 4 | 5 + (10-4) | 11 |
| Step / 步骤 | Action / 操作 | steps | energy | score |
|---|---|---|---|---|
| 0 | Start / 开始 | 0 | 10 | 0 |
| 1 | Hit wall / 撞墙 | ___ | ___ | ___ |
| 2 | Open space / 空地 | ___ | ___ | ___ |
| 3 | Hit monster / 撞怪物 | ___ | ___ | ___ |
| 4 | Hit wall / 撞墙 | ___ | ___ | ___ |
| Step / 步骤 | Action / 操作 | steps | energy | score |
|---|---|---|---|---|
| 0 | Start | 0 | 10 | 0 |
| 1 | Hit wall | 1 | 7 | 1+(10-7)=4 |
| 2 | Open space | 2 | 7 | 2+(10-7)=5 |
| 3 | Hit monster | 3 | 4 | 3+(10-4)=9 |
| 4 | Hit wall | 4 | 1 | 4+(10-1)=13 |
| Concept / 概念 | Description / 说明 | Code Example / 代码示例 |
|---|---|---|
| Variable / 变量 | Container for storing data / 存储数据的盒子 | steps = 0 |
| Initial value / 初始值 | Value at game start / 游戏开始时的值 | energy = 10 |
| Variable modification / 变量修改 | Changing a variable’s value / 改变变量的值 | steps = steps + 1 or steps += 1 |
| Shorthand / 简写 | Same meaning, shorter / 同一种意思 | steps += 1 |
| Formula calculation / 计算公式 | Calculate based on other variables / 根据其他变量计算 | score = steps + (10 - energy) |
global |
Modify outer variable inside function / 在函数内修改外部变量 | global steps |
| Conditional / 条件判断 | Decide whether to trigger change / 决定是否触发变化 | if hit_wall: |
📝 Practice Problems / 练习题
Problem 1 / 基础题 1
Write code to create a variable health with initial value 100, then subtract 30, and finally print the remaining health.
写出代码:创建一个变量 health 初始值为 100,然后减少 30,最后打印剩余生命值。
health = 100 health -= 30 print(health)
Problem 2 / 基础题 2
If steps=5, energy=8, initial_energy=10, what is the score using the original formula?
如果 steps=5, energy=8, initial_energy=10,按照原公式,score 是多少?
Problem 3 / 基础题 3
The player moves 4 times, with 2 of those moves hitting the wall. What are the final steps and energy? (Initial energy=10)
玩家移动了 4 次,其中 2 次撞墙。steps 和 energy 各是多少(初始 energy=10)?
Problem 4 / 进阶题 4
Write a function apply_damage(current_energy, damage) that returns the energy after damage, but cannot go below 0.
写一个函数 apply_damage(current_energy, damage),返回减少后的能量,但不能低于 0。
def apply_damage(current_energy, damage):
new_energy = current_energy - damage
if new_energy < 0:
return 0
return new_energy
Problem 5 / 进阶题 5
Write a loop that simulates the player moving until energy runs out. Each move has a 50% chance of hitting something (deduct 3 energy). Print the state after each step.
写一个循环,模拟玩家一直移动直到能量耗尽。每次移动有 50% 概率撞东西(扣 3 能量)。打印每一步的状态。
import random
steps = 0
energy = 10
while energy > 0:
steps += 1
if random.random() < 0.5:
energy -= 3
print(f"Step {steps}: Hit something, energy={energy}")
else:
print(f"Step {steps}: Safe, energy={energy}")
✅ Module 1 Complete! You have learned: tracking game state with variables, understanding initial values/triggers/change rules, calculating derived variables (score), using 'global' inside functions, and manually tracing variable changes.
✅ Module 1 完成!你学会了:用变量记录游戏状态、理解变量的初始值/触发条件/变化规则、用公式计算派生变量(如分数)、在函数内修改外部变量(global)、手动追踪变量的变化过程。
Module 2: Events & Conditional Statements
Learning Objectives: Understand what "events" are, learn to use conditional statements (if/elif/else) to handle different situations, and make programs respond differently to different inputs.
学习目标:理解什么是「事件」,学会用条件语句(if/elif/else)判断不同情况,让程序对不同的输入做出不同反应。
Prerequisite: Module 0 (variables, print, input), Module 1 (variable changes) · Estimated time: 1.5–2 hours
前置知识:Module 0(变量、print、输入)、Module 1(变量变化)· 预估时间:1.5–2小时
1. What are Events?
1. 什么是事件?
"Events" are things that happen. Your response depends on what event occurred:
「事件」就是发生的事情。你的反应取决于发生了什么事件:
| Event / 事件 | Your Response / 你的反应 | ||
|---|---|---|---|
| Alarm rings / 闹钟响了 | Get up / 起床 | ||
| Red light turns on / 红灯亮了 | Stop / 停车 | ||
| Phone receives message / 手机收到消息 | Check message / 查看消息 | ||
| Someone calls your name / 有人叫你的名字 | Turn around / 回头 |
| Event / 事件 | Program's Response / 程序的反应 | ||
|---|---|---|---|
| Player presses "←" key | Character moves left / 角色向左移动 | ||
| Player hits a wall | Energy decreases by 3 / 能量减少 3 | ||
| Timer counts one second | Countdown decreases by 1 / 倒计时减 1 | ||
| Player reaches the exit | Display "You win!" / 显示「你赢了!」 |
| Operator | Meaning | Example | Result |
|---|---|---|---|
== |
equal to / 等于 | 5 == 5 |
True |
!= |
not equal to / 不等于 | 5 != 3 |
True |
> |
greater than / 大于 | 10 > 5 |
True |
< |
less than / 小于 | 3 < 7 |
True |
>= |
greater than or equal to / 大于等于 | 5 >= 5 |
True |
<= |
less than or equal to / 小于等于 | 4 <= 5 |
True |
| Condition 1 (energy >= 10) | Condition 2 (has_key) | Result | |
|---|---|---|---|
| True | True | True | |
| True | False | False | |
| False | True | False | |
| False | False | False |
| Condition 1 | Condition 2 | Result | |
|---|---|---|---|
| True | True | True | |
| True | False | True | |
| False | True | True | |
| False | False | False |
| Concept / 概念 | Description / 说明 | Code Example / 代码示例 |
|---|---|---|
| Event / 事件 | Something that happens / 发生的事情 | key press, collision, timer |
if |
If condition is true / 如果条件成立 | if energy <= 0: |
else |
Otherwise / 否则 | else: |
elif |
Else if / 否则如果 | elif key == "SPACE": |
== |
Equal comparison / 等于比较 | if x == 10: |
!= |
Not equal / 不等于 | if x != 0: |
and |
Both conditions must be true / 两个条件都成立 | if a and b: |
or |
At least one condition is true / 至少一个成立 | if a or b: |
| Indentation / 缩进 | Defines code blocks / 表示代码块 | 4 spaces or Tab |
📝 Practice Problems / 练习题
Problem 1 / 基础题 1
Write code to determine if a number is positive, negative, or zero.
写出代码:判断一个数字 num 是否为正数、负数或零。
if num > 0:
print("Positive / 正数")
elif num < 0:
print("Negative / 负数")
else:
print("Zero / 零")
Problem 2 / 基础题 2
Write a condition: if energy >= 20 and has_potion == True, print "Can use ultimate".
写一个条件:如果 energy >= 20 并且 has_potion == True,打印「可以使用大招」。
if energy >= 20 and has_potion:
print("Can use ultimate / 可以使用大招")
Problem 3 / 基础题 3
Write code to determine if a year is a leap year (divisible by 4 but not by 100, or divisible by 400).
写出代码:判断一个年份是否是闰年(能被 4 整除但不能被 100 整除,或者能被 400 整除)。
if (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0):
print("Leap year / 闰年")
else:
print("Common year / 平年")
Problem 4 / 进阶题 4
Write a function get_grade(score) that returns the corresponding letter grade:
90-100: A, 80-89: B, 70-79: C, 60-69: D, 0-59: F.
写一个函数 get_grade(score),返回对应的等级。
def get_grade(score):
if score >= 90:
return "A"
elif score >= 80:
return "B"
elif score >= 70:
return "C"
elif score >= 60:
return "D"
else:
return "F"
Problem 5 / 进阶题 5
Write a function can_teleport(energy, has_teleport_item, is_special_zone) that returns whether teleport is possible.
Requirements: energy >= 20 OR has teleport item OR in special zone (free teleport).
写一个函数 can_teleport(energy, has_teleport_item, is_special_zone),返回是否可以使用传送:需要能量 >= 20 或者有传送道具 或者在特殊区域(免费传送)。
def can_teleport(energy, has_teleport_item, is_special_zone):
if energy >= 20 or has_teleport_item or is_special_zone:
return True
else:
return False
# More concise / 更简洁的写法
def can_teleport(energy, has_teleport_item, is_special_zone):
return energy >= 20 or has_teleport_item or is_special_zone
✅ Module 2 Complete! You have learned: what events and event-driven programming are, using if/elif/else for decisions, combining conditions with and/or, handling keyboard input and game collisions, and avoiding common conditional errors.
✅ Module 2 完成!你学会了:什么是事件和事件驱动编程、用 if / elif / else 做条件判断、用 and / or 组合多个条件、处理键盘输入和游戏碰撞事件、避免常见的条件语句错误。
Module 3: Loops & Functions
Learning Objectives: Understand loops (repeating code execution) and functions (packaging code for reuse), master for loops, while loops, function definition and calling, learn to iterate through data with loops and encapsulate repeated logic with functions.
学习目标:理解循环(重复执行代码)和方法(打包代码复用)的概念,掌握 for 循环、while 循环、函数的定义与调用,学会用循环遍历数据,用函数封装重复逻辑。
Prerequisite: Module 0, Module 1, Module 2 ·
前置知识:Module 0、Module 1、Module 2
Part 1: Loops / 第一部分:循环
1. Why Do We Need Loops?
1. 为什么需要循环?
Imagine you need to print numbers 1 to 100.
假设你需要打印 1 到 100 的数字。
# Without loops (too long) / 没有循环的方式(太长了)
print(1)
print(2)
print(3)
# ... would need 100 lines! / 要写 100 行!
# With loops (concise) / 有循环的方式(简洁)
for i in range(1, 101):
print(i)
Core understanding: Loops let you do repetitive things with just a few lines of code.
核心理解:循环让你用几行代码做重复的事情。
2. for Loop: When You Know How Many Times
2. for 循环:知道要重复多少次
for variable in range(times):
# Code to repeat / 重复执行的代码
Example 1: Print "Hello" 5 times / 打印 5 次 Hello
for i in range(5):
print("Hello")
Output / 输出:
Hello Hello Hello Hello Hello
Example 2: Print numbers 0 to 4 / 打印数字 0 到 4
for i in range(5):
print(i)
Output / 输出:
0 1 2 3 4
Note: range(5) produces 0, 1, 2, 3, 4 (5 numbers, starting from 0).
Example 3: Print 1 to 5 / 打印 1 到 5
for i in range(1, 6):
print(i)
Output / 输出:
1 2 3 4 5
range(start, stop) rules:
- Starts at
start/ 从 start 开始 - Ends before
stop(does NOT include stop) / 到 stop 之前结束(不包含 stop) - So
range(1, 6)includes 1,2,3,4,5
Example 4: Specify step / 指定步长
# Print even numbers from 0 to 10 / 打印 0 到 10 的偶数
for i in range(0, 11, 2):
print(i)
Output / 输出:
0 2 4 6 8 10
range(start, stop, step): increases by step each time.
3. Iterating Through Lists: for item in list
3. 遍历列表:for item in list
animals = ["Lion", "Frog", "Cat", "Dog"]
for animal in animals:
print(animal)
Output / 输出:
Lion Frog Cat Dog
Get both index and value: enumerate()
animals = ["Lion", "Frog", "Cat"]
for index, animal in enumerate(animals):
print(f"Index {index}: {animal}")
Output / 输出:
Index 0: Lion Index 1: Frog Index 2: Cat
4. while Loop: When You Don't Know How Many Times
4. while 循环:不知道次数,只知道什么时候停止
while condition:
# Code repeats while condition is True
# 条件为 True 时重复执行
Example 1: Countdown / 倒计时
countdown = 5
while countdown > 0:
print(countdown)
countdown = countdown - 1
print("Blast off! / 发射!")
Output / 输出:
5 4 3 2 1 Blast off! / 发射!
Example 2: Keep moving until energy runs out / 能量耗尽前一直移动
energy = 10
while energy > 0:
print(f"Current energy: {energy} / 当前能量: {energy}")
energy -= 3
print("Energy exhausted, game over / 能量耗尽,游戏结束")
Output / 输出:
Current energy: 10 / 当前能量: 10 Current energy: 7 / 当前能量: 7 Current energy: 4 / 当前能量: 4 Current energy: 1 / 当前能量: 1 Energy exhausted, game over / 能量耗尽,游戏结束
Example 3: Wait for correct user input / 等待用户输入正确指令
command = ""
while command != "quit":
command = input("Enter command (quit to exit) / 输入命令(quit 退出): ")
print(f"You entered: {command} / 你输入了: {command}")
5. for vs while: When to Use Which?
5. for vs while:什么时候用哪个?
| Scenario / 场景 | Use / 用什么 | Reason / 原因 | |
|---|---|---|---|
| Iterate through all list elements / 遍历列表所有元素 | for |
Know how many times / 知道要循环多少次 | |
| Print 1 to 100 / 打印 1 到 100 | for |
Know the count / 知道次数 | |
| Continue while energy > 0 / 能量大于 0 时继续 | while |
Don't know how many iterations / 不知道会循环多少次 | |
| Wait for correct user input / 等待用户输入正确内容 | while |
Don't know when user will input correctly / 不知道用户什么时候输入正确 |
| Function | Purpose | Example | Result |
|---|---|---|---|
len() |
Get length / 获取长度 | len([1,2,3]) |
3 |
type() |
Get type / 获取类型 | type(10) |
<class 'int'> |
int() |
Convert to integer / 转换为整数 | int("5") |
5 |
str() |
Convert to string / 转换为字符串 | str(5) |
"5" |
float() |
Convert to float / 转换为小数 | float("3.14") |
3.14 |
sum() |
Sum of list / 求和 | sum([1,2,3]) |
6 |
max() |
Maximum value / 最大值 | max([1,5,3]) |
5 |
min() |
Minimum value / 最小值 | min([1,5,3]) |
1 |
| Concept / 概念 | Description / 说明 | Code Example / 代码示例 |
|---|---|---|
| for loop / for 循环 | Repeat a fixed number of times / 重复指定次数 | for i in range(10): |
| Iterate list / 遍历列表 | Process each item in sequence / 依次处理每个元素 | for item in my_list: |
| while loop / while 循环 | Repeat while condition is true / 条件成立时重复 | while energy > 0: |
break |
Exit loop early / 提前结束循环 | if found: break |
continue |
Skip current iteration / 跳过本次循环 | if even: continue |
| Function definition / 函数定义 | Define a reusable code block / 定义可复用的代码块 | |
def |
Define function / 定义函数 | def my_func(): |
| Parameters / 参数 | Values passed to function / 传给函数的值 | def add(a, b): |
| Return value / 返回值 | Result returned from function / 函数返回的结果 | return result |
global |
Modify global variable / 修改全局变量 | global energy |
| Local variable / 局部变量 | Variable inside function / 函数内部的变量 | x = 10 (inside function) |
📝 Practice Problems / 练习题
Problem 1 / 基础题 1
Use a for loop to print all odd numbers from 1 to 20.
用 for 循环打印 1 到 20 之间的所有奇数。
for i in range(1, 21, 2):
print(i)
Problem 2 / 基础题 2
Use a while loop to print the 5 times table (5×1 to 5×10).
用 while 循环打印 5 的乘法表(5×1 到 5×10)。
i = 1
while i <= 10:
print(f"5 × {i} = {5 * i}")
i += 1
Problem 3 / 基础题 3
Write a function max_of_two(a, b) that returns the larger of two numbers.
写一个函数 max_of_two(a, b),返回两个数中较大的那个。
def max_of_two(a, b):
if a > b:
return a
else:
return b
Problem 4 / 基础题 4
Given the list [15, 22, 8, 19, 31, 7], use a loop to find the maximum value (without using the max() function).
给定列表 [15, 22, 8, 19, 31, 7],用循环找出最大值(不用 max() 函数)。
numbers = [15, 22, 8, 19, 31, 7]
max_num = numbers[0]
for num in numbers:
if num > max_num:
max_num = num
print(max_num) # 31
Problem 5 / 进阶题 5
Write a function is_palindrome(word) that checks whether a string is a palindrome (reads the same forwards and backwards, e.g., "radar").
写一个函数 is_palindrome(word),判断一个字符串是否是回文(正读反读一样,如 "radar")。
def is_palindrome(word):
# Method 1: Compare with reversed string / 方法1:比较原字符串和反转后的字符串
return word == word[::-1]
# Test / 测试
print(is_palindrome("radar")) # True
print(is_palindrome("hello")) # False
Problem 6 / 进阶题 6
Write a function count_vowels(text) that counts the number of vowels (a, e, i, o, u) in a string.
写一个函数 count_vowels(text),统计字符串中元音字母(a, e, i, o, u)的数量。
def count_vowels(text):
vowels = "aeiouAEIOU"
count = 0
for char in text:
if char in vowels:
count += 1
return count
print(count_vowels("Hello World")) # 3 (e, o, o)
✅ Module 3 Complete! You have learned: using for loops to iterate through data and control repetition count, using while loops for unknown repetition counts, controlling loops with break and continue, defining and calling functions (parameters, return values), understanding the difference between global and local variables, and solving real problems by combining loops and functions.
✅ Module 3 完成!你学会了:用 for 循环遍历数据和控制次数,用 while 循环处理未知次数的重复,用 break 和 continue 控制循环流程,定义和调用函数(参数、返回值),理解全局变量和局部变量的区别,用循环 + 函数的组合解决实际问题。
Module 4: Lists & List Methods
Learning Objectives: Understand what lists are, how to store multiple items in a list, master list indexing, common methods (add, remove, modify, search), and learn to iterate through list data.
学习目标:理解列表是什么,如何用列表存储多个数据,掌握列表的索引访问、常用方法(添加、删除、修改、查找),学会遍历列表和处理列表数据。
Prerequisite: Module 0 (variables, print), Module 3 (for loops)
前置知识:Module 0(变量、print)、Module 3(for 循环)
1. Why Do We Need Lists?
1. 为什么需要列表?
The problem without lists / 没有列表的问题:
player1 = "Alice" player2 = "Bob" player3 = "Charlie" # ... would need 10 variables! / 要写 10 个变量!
Solution with lists / 用列表解决:
players = ["Alice", "Bob", "Charlie", "David", "Eve",
"Frank", "Grace", "Henry", "Ivy", "Jack"]
Core understanding: A list is a container that can hold multiple items, managed with a single variable.
核心理解:列表是一个容器,可以放多个数据,用一个变量管理所有数据。
2. Creating Lists
2. 创建列表
# Empty list / 空列表 empty_list = [] # Lists with elements / 包含元素的列表 numbers = [1, 2, 3, 4, 5] names = ["Alice", "Bob", "Charlie"] mixed = [10, "Hello", 3.14, True] # Lists can mix types / 列表可以混合不同类型
3. Accessing List Elements: Index
3. 访问列表元素:索引(Index)
fruits = ["apple", "banana", "orange", "grape", "mango"] # Index: 0 1 2 3 4
Accessing by index / 通过索引获取元素:
print(fruits[0]) # apple print(fruits[2]) # orange print(fruits[4]) # mango
Negative indices (from the end) / 负数索引(从后往前):
print(fruits[-1]) # mango (last / 最后一个) print(fruits[-2]) # grape (second from last / 倒数第二个) print(fruits[-5]) # apple (first / 第一个)
Modifying elements / 修改元素:
fruits[1] = "blueberry" print(fruits) # ['apple', 'blueberry', 'orange', 'grape', 'mango']
4. List Length: len()
4. 列表长度:len()
fruits = ["apple", "banana", "orange"] print(len(fruits)) # 3
Important: The last element's index = len(list) - 1.
5. Iterating Through Lists
5. 遍历列表
Method 1: Iterate over values directly / 直接遍历值
fruits = ["apple", "banana", "orange"]
for fruit in fruits:
print(fruit)
Method 2: Iterate over indices / 遍历索引
for i in range(len(fruits)):
print(f"Index {i}: {fruits[i]}")
Method 3: Using enumerate() (get both index and value)
for i, fruit in enumerate(fruits):
print(f"Index {i}: {fruit}")
6. Common List Methods
6. 列表常用方法
append(): Add to the end / 在末尾添加元素
fruits = ["apple", "banana"]
fruits.append("orange")
print(fruits) # ['apple', 'banana', 'orange']
insert(): Insert at specific position / 在指定位置插入
fruits = ["apple", "orange"] fruits.insert(1, "banana") # Insert at index 1 / 在索引 1 的位置插入 print(fruits) # ['apple', 'banana', 'orange']
pop(): Remove at index and return it / 删除指定位置的元素(并返回它)
fruits = ["apple", "banana", "orange"] removed = fruits.pop(1) # Remove at index 1 / 删除索引 1 的元素 print(removed) # banana print(fruits) # ['apple', 'orange'] # Without index, removes last / 不指定索引时,删除最后一个 last = fruits.pop() print(last) # orange print(fruits) # ['apple']
remove(): Remove first matching value / 删除第一个匹配的值
fruits = ["apple", "banana", "apple", "orange"]
fruits.remove("apple") # Removes first "apple" / 删除第一个 apple
print(fruits) # ['banana', 'apple', 'orange']
index(): Find index of an element / 查找元素的索引
fruits = ["apple", "banana", "orange"]
pos = fruits.index("banana")
print(pos) # 1
# If element doesn't exist, ValueError / 如果元素不存在,会报错
in operator: Check if element exists / 检查元素是否存在
print("banana" in fruits) # True
print("grape" in fruits) # False
sort(): Sort in place / 排序(改变原列表)
numbers = [3, 1, 4, 1, 5, 9] numbers.sort() print(numbers) # [1, 1, 3, 4, 5, 9] # Descending order / 降序 numbers.sort(reverse=True) print(numbers) # [9, 5, 4, 3, 1, 1]
reverse(): Reverse the list / 反转列表
fruits = ["apple", "banana", "orange"] fruits.reverse() print(fruits) # ['orange', 'banana', 'apple']
7. List Operations Cheat Sheet
7. 列表操作速查表
| Operation / 操作 | Code / 代码 | Result / 结果 |
|---|---|---|
| Create list / 创建列表 | my_list = [1, 2, 3] |
[1, 2, 3] |
| Access element / 访问元素 | my_list[0] |
1 |
| Modify element / 修改元素 | my_list[0] = 10 |
[10, 2, 3] |
| Add to end / 末尾添加 | my_list.append(4) |
[10, 2, 3, 4] |
| Insert / 插入 | my_list.insert(1, 5) |
[10, 5, 2, 3, 4] |
| Remove by index / 按位置删除 | my_list.pop(2) |
Returns 2, list becomes [10, 5, 3, 4] |
| Remove by value / 按值删除 | my_list.remove(5) |
[10, 3, 4] |
| Find index / 查找索引 | my_list.index(3) |
1 |
| Check existence / 检查存在 | 3 in my_list |
True |
| Length / 长度 | len(my_list) |
3 |
| Sort / 排序 | my_list.sort() |
[3, 4, 10] |
| Reverse / 反转 | my_list.reverse() |
[10, 4, 3] |
| Concept / 概念 | Description / 说明 | Code Example / 代码示例 |
|---|---|---|
| Create list / 创建列表 | Use square brackets / 用方括号 | my_list = [1, 2, 3] |
| Index access / 索引访问 | Start from 0 / 从 0 开始 | my_list[0] |
| Negative index / 负数索引 | From the end / 从后往前 | my_list[-1] |
| Modify element / 修改元素 | Assign value / 赋值 | my_list[0] = 10 |
| Length / 长度 | len() |
len(my_list) |
| Iterate / 遍历 | for loop / for 循环 | for item in my_list: |
| Add to end / 末尾添加 | append() |
my_list.append(4) |
| Insert / 插入 | insert() |
my_list.insert(1, 5) |
| Remove by index / 按位置删除 | pop() |
my_list.pop(2) |
| Remove by value / 按值删除 | remove() |
my_list.remove(5) |
| Find index / 查找索引 | index() |
my_list.index(3) |
| Check existence / 检查存在 | in operator |
3 in my_list |
| Sort / 排序 | sort() |
my_list.sort() |
| Reverse / 反转 | reverse() |
my_list.reverse() |
| Slicing / 切片 | [start:end:step] |
my_list[1:4] |
📝 Practice Problems / 练习题
Problem 1 / 基础题 1
Create list [10, 20, 30, 40, 50], then: print the third element, change the second element to 25, add 60 to the end.
创建列表 [10, 20, 30, 40, 50],然后:打印第三个元素,修改第二个元素为 25,在末尾添加 60。
numbers = [10, 20, 30, 40, 50] print(numbers[2]) # 30 numbers[1] = 25 numbers.append(60) print(numbers) # [10, 25, 30, 40, 50, 60]
Problem 2 / 基础题 2
Given [5, 2, 8, 1, 9, 3], find the maximum and minimum values (without using max() and min()).
给定列表 [5, 2, 8, 1, 9, 3],找出最大值和最小值(不用 max() 和 min())。
numbers = [5, 2, 8, 1, 9, 3]
max_num = numbers[0]
min_num = numbers[0]
for num in numbers:
if num > max_num:
max_num = num
if num < min_num:
min_num = num
print(f"Max: {max_num}, Min: {min_num}") # Max: 9, Min: 1
Problem 3 / 基础题 3
Write a function reverse_list(my_list) that returns a reversed list (cannot use reverse() method).
写一个函数 reverse_list(my_list),返回反转后的列表(不能使用 reverse() 方法)。
def reverse_list(my_list):
reversed_list = []
for i in range(len(my_list) - 1, -1, -1):
reversed_list.append(my_list[i])
return reversed_list
print(reverse_list([1, 2, 3, 4])) # [4, 3, 2, 1]
Problem 4 / 进阶题 4
Write a function remove_duplicates(my_list) that returns a list with duplicates removed.
写一个函数 remove_duplicates(my_list),返回去除重复元素后的列表。
def remove_duplicates(my_list):
result = []
for item in my_list:
if item not in result:
result.append(item)
return result
print(remove_duplicates([1, 2, 2, 3, 3, 3, 4])) # [1, 2, 3, 4]
Problem 5 / 进阶题 5
Implement a simple Todo List program using a list with functions: add task, view all tasks, complete task (delete), exit.
用列表实现一个简单的待办事项(Todo List)程序:添加任务、查看所有任务、完成任务(删除)、退出。
todos = []
while True:
print("\n=== Todo List / 待办事项 ===")
print("1. Add task / 添加任务")
print("2. View tasks / 查看任务")
print("3. Complete task / 完成任务")
print("4. Exit / 退出")
choice = input("Choose / 选择: ")
if choice == "1":
task = input("Enter task / 输入任务: ")
todos.append(task)
print(f"Added: {task} / 已添加: {task}")
elif choice == "2":
if len(todos) == 0:
print("No tasks / 暂无任务")
else:
for i, task in enumerate(todos):
print(f"{i+1}. {task}")
elif choice == "3":
if len(todos) == 0:
print("No tasks / 暂无任务")
else:
for i, task in enumerate(todos):
print(f"{i+1}. {task}")
num = int(input("Complete which one? / 完成第几个?")) - 1
if 0 <= num < len(todos):
removed = todos.pop(num)
print(f"Completed: {removed} / 已完成: {removed}")
else:
print("Invalid / 无效")
elif choice == "4":
print("Goodbye! / 再见!")
break
else:
print("Invalid choice / 无效选择")
✅ Module 4 Complete! You have learned: creating and accessing lists, manipulating list elements with index operations, common list methods (append, insert, pop, remove, index, sort, reverse), multiple ways to iterate through lists, storing game data with lists (inventory, player config, maze maps), and list slicing.
✅ Module 4 完成!你学会了:创建和访问列表、用索引操作列表元素、列表的常用方法(append、insert、pop、remove、index、sort、reverse)、遍历列表的多种方式、用列表存储游戏数据(物品栏、玩家配置、迷宫地图)、列表切片操作。
Module 5: File I/O & Object-Oriented Programming
Learning Objectives: Learn to read configuration data from CSV files, understand the concept of separating data from code, master basic file operations, get an introduction to classes and objects, and apply knowledge from previous modules to complete a small project.
学习目标:学会从 CSV 文件读取配置数据,理解数据与代码分离的思想,掌握文件操作的基本方法,了解类和对象的入门概念,能够综合运用前四个 Module 的知识完成一个小型项目。
Prerequisite: Modules 0-4 · Estimated time: 2.5–3 hours
前置知识:Module 0-4 全部内容 · 预估时间:2.5–3小时
Part 1: Why Do We Need Files?
第一部分:为什么需要文件?
1. From Hardcoded to File Configuration
1. 从硬编码到文件配置
The old way (hardcoded) / 之前的方式(硬编码):
# Configuration written in code / 配置写在代码里 player_name = "Haoran" width = 20 height = 15 monster_count = 10 wall_count = 8 energy = 10
Problems / 问题:
- Need to change code to change configuration / 每次改配置都要改代码
- Different players need different configurations → many copies of code / 不同玩家需要不同的配置 → 需要很多份代码
- Code and data mixed together, hard to maintain / 代码和数据混在一起,不好维护
Better approach (separate data from code) / 更好的方式(数据与代码分离):
Code / 代码(Code)← Reads → File / 文件(Data/Config)
Benefits / 好处:
- Change configuration by changing the file, not the code / 代码不用改,只改文件就能换配置
- One file can store many player configurations / 一个文件可以存很多玩家的配置
- Non-programmers can modify configuration / 非程序员也可以修改配置(不需要懂代码)
Part 2: CSV File Format
第二部分:CSV 文件格式
2. What is CSV?
2. 什么是 CSV?
CSV = Comma-Separated Values(逗号分隔值)
CSV file example: playerCustomisation.csv
PlayerNumber,Width,Height,MonsterCount,WallCount,Energy,Animal,Sound 0,20,15,10,8,10,Lion,Roar 1,25,20,12,10,15,Tiger,Growl 2,18,12,8,6,12,Frog,Croak 3,22,18,11,9,13,Cat,Meow 4,20,15,9,7,11,Dog,Bark
| Part / 部分 | Description / 说明 | Example / 例子 |
|---|---|---|
| First row (header) / 第一行(表头) | Column names, describes each column / 列名,描述每列是什么 | PlayerNumber, Width, Height, ... |
| Subsequent rows (data rows) / 后续行(数据行) | Actual data, one record per row / 实际的数据,每行一条记录 | 0,20,15,10,8,10,Lion,Roar |
| Comma / 逗号 | Separates each column / 分隔每一列 | 20,15,10 means three columns |
| Function | Purpose | Example |
|---|---|---|
int() |
Convert to integer / 转整数 | int("10") → 10 |
float() |
Convert to float / 转小数 | float("3.14") → 3.14 |
str() |
Convert to string / 转字符串 | str(10) → "10" |
| Concept | Analogy / 类比 | Description / 说明 |
|---|---|---|
| Class / 类 | Cookie cutter / 饼干模具 | Defines a template for a type of thing / 定义了一类事物的模板 |
| Object / 对象 | Cookie made from cutter / 做出来的饼干 | Specific instance created from the template / 根据模板创建的具体实例 |
| Concept / 概念 | Code Example / 代码示例 |
|---|---|
| CSV file / CSV 文件 | data.csv |
| Import module / 导入模块 | import csv |
| Open file (read) / 打开文件(读取) | with open("file.csv", "r") as f: |
| Create reader / 创建读取器 | reader = csv.reader(f) |
| Read header / 读取表头 | header = next(reader) |
| Find index / 查找索引 | header.index("column_name") |
| Iterate rows / 遍历行 | for row in reader: |
| Type conversion / 类型转换 | int(row[0]) |
| Create writer / 创建写入器 | writer = csv.writer(f) |
| Write row / 写入一行 | writer.writerow(row) |
| Class / 类 | class Player: |
| Object / 对象 | p = Player("name", 10) |
| Attribute / 属性 | p.name |
| Method / 方法 | p.move() |
📝 Practice Problems / 练习题
Problem 1 / 基础题 1
Write the first three steps to read a CSV file (import module, open file, create reader).
写出读取 CSV 文件前三步的代码(导入模块、打开文件、创建读取器)。
import csv
with open("file.csv", "r") as f:
reader = csv.reader(f)
Problem 2 / 基础题 2
If header = ["A", "B", "C", "D"], what does header.index("C") return?
假设 header = ["A", "B", "C", "D"],header.index("C") 返回什么?
Problem 3 / 基础题 3
Why do we need to use int() to convert numbers read from CSV?
为什么要用 int() 转换 CSV 读取的数字?
csv.reader() reads all data as strings, so you need to convert to integers for mathematical operations.因为 csv.reader() 读取的所有数据都是字符串类型,需要转换成整数才能进行数学运算。
Problem 4 / 进阶题 4
Write a function read_first_n_rows(file_name, n) that returns the first n rows of a CSV file (including the header).
写一个函数 read_first_n_rows(file_name, n),返回 CSV 文件的前 n 行(包含表头)。
import csv
def read_first_n_rows(file_name, n):
rows = []
with open(file_name, "r") as f:
reader = csv.reader(f)
for i, row in enumerate(reader):
if i >= n:
break
rows.append(row)
return rows
Problem 5 / 进阶题 5
Write a function filter_by_column(file_name, column_name, value) that returns all rows where the specified column equals the given value.
写一个函数 filter_by_column(file_name, column_name, value),返回 CSV 中指定列等于某值的所有行。
import csv
def filter_by_column(file_name, column_name, value):
results = []
with open(file_name, "r") as f:
reader = csv.reader(f)
header = next(reader)
if column_name not in header:
return results
col_index = header.index(column_name)
for row in reader:
if len(row) > col_index and row[col_index] == str(value):
results.append(row)
return results
🎉 Congratulations! You have completed all 5 Modules! / 恭喜!你完成了全部 5 个 Module 的学习!
You now have mastered: Python basic syntax, variables and state management, conditional statements and event handling, loops and functions, list data operations, file reading and data processing, and an introduction to classes and objects.
你现在掌握了:Python 基础语法、变量和状态管理、条件判断和事件处理、循环和函数、列表数据操作、文件读取和数据处理、类和对象的入门概念。
These skills are sufficient to complete PROG1001 Assessment 1, 2, and 3.
这些知识足以完成 PROG1001 的 Assessment 1、2、3。