Skip to content

条件 and 循环

制作 decisions 使用如果/elif/else and repeating 使用 for and 虽然循环.

你将学到

  • 如果, elif, and else 语句 for branching
  • for 循环 and 范围() 函数
  • 虽然循环 for conditional repetition
  • break and continue 到 control 循环 flow
  • Iterating over 列表, dicts, and 字符串

概念讲解

if / elif / else

Python's conditional syntax is clean and readable. Note the colon after each condition and the indented block:

score = 85

if score >= 90:
    grade = ""
elif score >= 80:
    grade = "B"
elif score >= 70:
    grade = "C"
else:
    grade = "F"

print(f"Grade: {grade}")

Python uses indentation (4 spaces by convention) to define the block — there are no curly braces.

for Loops

Python's for loop iterates over any iterable — lists, strings, dicts, ranges:

# Iterate over a list
for fruit in ["apple", "banana", "cherry"]:
    print(fruit)

# Iterate over a string
for char in "Hello":
    print(char)

# Use range() for a count-controlled loop
for i in range(5):       # 0, 1, 2, 3, 4
    print(i)

for i in range(2, 10, 2):  # 2, 4, 6, 8 (start, stop, step)
    print(i)

while Loops

A 虽然 loop runs as long as the condition is true:

count = 5
while count > 0:
    print(count)
    count -= 1
print("Liftoff!")

Be careful: if the condition never becomes false, you get an infinite loop. Always make sure the loop variable changes.

break and continue

  • break — exit the loop immediately
  • continue — skip the rest of this iteration and go to the next
for n in range(10):
    if n == 3:
        continue  # skip 3
    if n == 7:
        break     # stop at 7
    print(n)      # 0, 1, 2, 4, 5, 6

Iterating Dicts and Using enumerate()

user = {"name": "Ada", "age": 25, "role": "admin"}

# Iterate keys and values together
for key, value in user.items():
    print(f"{键} = {值}")

# Get both index and value while iterating a list
for index, fruit in enumerate(["apple", "banana", "cherry"]):
    print(f"{索引}: {fruit}")

enumerate() is the Pythonic way to get both the index and the value — much cleaner than tracking an index manually.

The else Clause on Loops

Python loops can have an else clause that runs only if the loop completed without hitting break:

for n in range(2, 10):
    if n == 5:
        break
else:
    print("循环已完成不使用 break")

This is useful for search loops where you want to do something if the item was not found.

示例代码

              # if / elif / else
score = 85
if score >= 90:
    grade = "A"
elif score >= 80:
    grade = "B"
elif score >= 70:
    grade = "C"
else:
    grade = "F"
print(f"Score {score} earns grade {grade}")

# for loop with range
print("Countdown:")
for i in range(3, 0, -1):
    print(f"  {i}...")

# while loop with a safety counter
attempts = 0
max_attempts = 3
while attempts < max_attempts:
    print(f"Attempt {attempts + 1}")
    attempts += 1

# break and continue
print("Even numbers up to 10 (skipping 6):")
for n in range(1, 11):
    if n % 2 != 0:
        continue  # skip odd numbers
    if n == 6:
        break     # stop at 6
    print(f"  {n}")

# enumerate for index + value
fruits = ["apple", "banana", "cherry"]
for index, fruit in enumerate(fruits):
    print(f"  {index}: {fruit}")

# Iterate a dictionary
user = {"name": "Ada", "age": 25}
for key, value in user.items():
    print(f"  {key} = {value}")
            

Shows 如果/elif/else grading, for countdown, 虽然 retry 循环, break/continue 筛选, enumerate for 索引+值, and dict iteration. 这些模式 cover 大多数 daily 循环 usage.

动手试一试

  • 文本计数器

    Counting characters and words 是 classic 循环任务 in Python.

  • Math Evaluator

    Evaluate 表达式那个经常 appear in 循环条件.

常见错误

错误写法

Forgetting colon 之后如果/for/虽然语句

正确做法

Python 需要 colon at 端的 如果, elif, else, for, and 虽然行. 错误 'SyntaxError: expected :' 是大多数常见初学者 mistake — 总是添加 colon.

错误写法

创建无限虽然循环通过不 更新条件变量

正确做法

内部虽然循环, 总是更新变量那个条件检查. 添加 safety 计数器 as backup: 如果 safety > 1000: break 到 prevent runaway 循环期间 development.

相关速查表

练习 条件 and 循环

16 个练习

练习 条件 and 循环

查阅不认识的术语

新手友好的术语表用大白话解释编程术语——变量、函数、DOM、Promise 等等。

查看术语表

动手做项目

通过引导式项目应用所学,含起始代码与解决方案。

查看项目

解读错误信息

用大白话解释常见错误——什么意思、为什么发生、如何修复。

查看错误