Welcome / 欢迎

Interactive review for Python Class 2. Select a topic from the left to begin.

欢迎使用 Python 第2课交互式复习应用。请从左侧选择一个主题开始。

Instructions

  • Navigate using the sidebar.
  • Read the bilingual explanations.
  • Click Run to execute code simulations.

1. Variables & Indexing

In Python, strings are sequences. We access characters using 0-based indexing.

在 Python 中,字符串是序列。我们使用基于0的索引访问字符。
text = "today is our 2 lesson"

print(text[0])
print(text[13])

Iteration:

for i in range(len(text)):
  print(text[i])

2. List Operations

Operators + and * behave differently on lists than numbers.

+* 运算符在列表上的行为与数字不同。
l1 = [2, 3]; l2 = [1, 2]

print(l2 + l1) # Join
print(l2 * 10) # Repeat

3. Loops & Modification

To modify a list in place, loop using range(len(list)).

要就地修改列表,请使用 range(len(list)) 进行循环。
nums = [1, 2, 3, 4]

# Divide every number by 10
for i in range(len(nums)):
  nums[i] = nums[i] / 10

print(nums)

4. Algorithms (Min/Max)

Finding the smallest number: Manual Algorithm vs. Built-in Functions.

寻找最小数:手动算法 vs 内置函数。

Manual Logic

guess = list[0]
for x in list:
  if guess > x: guess = x

Built-in (Recommended)

print(max(list))
print(min(list))

5. String Parsing

Extracting numerical data from text.

从文本中提取数值数据。
text = "4 students, 2 postdocs"
sum = 0
for w in text.split():
  if w.isdigit():
    sum += int(w)

6. Common Errors

TypeError

Caused by naming a variable max (shadowing).

NameError

Caused by using a list before creating it [].

7. Mutability Trap

Lists are mutable. b = a links them together.

列表是可变的。b = a 将它们链接在一起。

Integer (Safe)

a=1; b=a; a=2; print(b)

List (Trap!)

a=[1]; b=a; a[0]=2; print(b)

8. File I/O

Reading and writing files. Modes: "w" (write), "a" (append), "r" (read).

读写文件。模式:"w"(写入),"a"(追加),"r"(读取)。

Virtual File Content

9. Visualization

Interactive equivalent of matplotlib.pyplot.

matplotlib.pyplot 的交互式等效项。
import matplotlib.pyplot as plt
x = [1, 2, 3, 4]
y = [1, 2, 3, 4]
plt.plot(x, y)