Python for Loop

Python3 循环语句Python3 Loop Statements


forIt is the most commonly used loop statement in Python, used to iterate over iterable objects (sequences, dictionaries, sets, etc.).

Python'sforloops are more concise and powerful than languages like C/C++, with no need to manually manage loop variables, directly iterating over elements.

Word Meaning: forMeans "for, regarding", used for iterative traversal.


Basic Syntax and Parameters

Syntax Format

for 变量 in 可迭代对象:
    代码块

Syntax Explanation

  • Variable: The element taken from the iterable object each loop iteration.
  • Iterable object: Lists, tuples, strings, dictionaries, sets, range, etc.
  • Indentation: The loop body must be indented.

else Clause

  • Optional: The for loop can have an else clause.
  • Execution timing: Executes when the loop ends normally (not exited by break).

Examples

Example 1: Iterating Over a List

Examples

# Iterate over a list
fruits = ["apple", "banana", "orange"]

for fruit in fruits:
    print(fruit)

# Iterate with index
for i, fruit in enumerate(fruits):
    print(f"{i}: {fruit}")

Expected output:

苹果
香蕉
橙子
0: 苹果
1: 香蕉
2: 橙子

Code analysis:

  1. The for loop directly iterates over each element in the list.
  2. enumerate() provides both index and value.

Example 2: Iterating Over Strings and Tuples

Examples

# Iterate over a string
for char in "Python":
    print(char, end=" ")
print()  # Newline

# Iterate over a tuple
point = (10, 20)
for value in point:
    print(value, end=" ")
print()

Expected output:

P y t h o n
10 20

Strings and tuples are also iterable.

Example 3: Iterating Over Dictionaries

Examples

# Iterate over a dictionary (iterates keys by default)
person = {"name": "Tom", "age": 20, "city": "Beijing"}

for key in person:
    print(key)

print("---")

# Iterate over key-value pairs
for key, value in person.items():
    print(f"{key}: {value}")

print("---")

# Iterate over values only
for value in person.values():
    print(value)

Expected output:

name
age
city
---
name: Tom
age: 20
city: Beijing
---
Tom
20
Beijing

The dictionary's items(), keys(), and values() methods can iterate over different parts.

Example 4: for Loop with else

Examples

# for-else structure
for i in range(3):
    print(i)
else:
    print("Loop ended normally")

print("---")

# else is not executed when break occurs
for i in range(5):
    if i == 3:
        break
    print(i)
else:
    print("This line will not print")

Expected output:

0
1
2
循环正常结束
---
0
1
2

In a for-else structure, the else clause does not execute when the loop is terminated by break.

Example 5: Nested Loops

Examples

# Nested loop - print multiplication table
for i in range(1, 10):
    for j in range(1, i + 1):
        print(f"{j}*{i}={i*j}", end="\t")
    print()

Expected output:

1*1=1
1*2=2    2*2=4
1*3=3    2*3=6    3*3=9
...

Nested loops can be used to process multi-dimensional data structures or generate tables.


Python3 循环语句Python3 Loop Statements

Other Extensions