Fundamentals 9 min read

Understanding Loop Structures in Python: for‑in and while Loops

This article explains why loops are needed in programming, introduces Python's for‑in and while loops with practical examples such as summing numbers, generating multiplication tables, guessing games, and solving prime and GCD/LCM problems, and discusses break, continue, and nested loops.

Python Programming Learning Circle
Python Programming Learning Circle
Python Programming Learning Circle
Understanding Loop Structures in Python: for‑in and while Loops

When writing programs we often encounter scenarios that require repeatedly executing certain instructions, such as continuously moving a robot toward the goal until it possesses the ball and is within shooting range.

In such cases a loop structure is needed. Python provides two loop constructs: the for‑in loop and the while loop.

for‑in loop

If the number of iterations is known, the for‑in loop is recommended. For example, to calculate the sum of numbers from 1 to 100:

<code>"""
Use a for loop to compute the sum of 1~100
"""
total = 0
for x in range(1, 101):
    total += x
print(total)
</code>

The range(1, 101) generates a sequence from 1 to 100. Variants of range allow different start points, end points, and step sizes, e.g.:

range(101) – generates 0‑100 (101 is excluded).

range(1, 101) – generates 1‑100 (closed at the start, open at the end).

range(1, 101, 2) – generates odd numbers between 1 and 100.

range(100, 0, -2) – generates even numbers from 100 down to 2.

Using these variants we can sum only the even numbers between 1 and 100:

<code>"""
Use a for loop to sum even numbers between 1~100
"""
total = 0
for x in range(2, 101, 2):
    total += x
print(total)
</code>

while loop

When the number of iterations is not known in advance, a while loop is appropriate. It repeats as long as a Boolean expression evaluates to True . A classic example is a number‑guessing game:

<code>"""
Guess the number game
"""
import random
answer = random.randint(1, 100)
counter = 0
while True:
    counter += 1
    number = int(input('请输入: '))
    if number < answer:
        print('大一点')
    elif number > answer:
        print('小一点')
    else:
        print('恭喜你猜对了!')
        break
print(f'你总共猜了{counter}次')
</code>

The keywords break and continue control loop flow. break exits the nearest loop, while continue skips the remaining statements in the current iteration and proceeds to the next one.

Nested loops

Loops can be nested just like conditional statements. The following example prints the multiplication table (九九表) using two nested for loops:

<code>"""
Print multiplication table
"""
for i in range(1, 10):
    for j in range(1, i + 1):
        print(f'{i}*{j}={i * j}', end='\t')
    print()
</code>

Here the outer loop controls the number of rows, and the inner loop prints the columns for each row.

Additional examples

1. Determine whether a positive integer is a prime number:

<code>"""
Check if a positive integer is prime
"""
num = int(input('请输入一个正整数: '))
end = int(num ** 0.5)
is_prime = True
for x in range(2, end + 1):
    if num % x == 0:
        is_prime = False
        break
if is_prime and num != 1:
    print(f'{num}是素数')
else:
    print(f'{num}不是素数')
</code>

2. Compute the greatest common divisor (GCD) and least common multiple (LCM) of two positive integers:

<code>"""
Calculate GCD and LCM of two numbers
"""
x = int(input('x = '))
y = int(input('y = '))
if x > y:
    x, y = y, x  # swap to ensure x <= y
for factor in range(x, 0, -1):
    if x % factor == 0 and y % factor == 0:
        print(f'{x}和{y}的最大公约数是{factor}')
        print(f'{x}和{y}的最小公倍数是{x * y // factor}')
        break
</code>

Summary

By mastering Python's conditional and loop structures, we can solve many practical problems. Use for when the iteration count is known, while when it is not, and employ break to exit loops early or continue to skip to the next iteration. Nested loops enable more complex patterns such as multiplication tables.

programmingfundamentalsloopsfor loopwhile loop
Python Programming Learning Circle
Written by

Python Programming Learning Circle

A global community of Chinese Python developers offering technical articles, columns, original video tutorials, and problem sets. Topics include web full‑stack development, web scraping, data analysis, natural language processing, image processing, machine learning, automated testing, DevOps automation, and big data.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.