Fundamentals 9 min read

Understanding Loop Structures in Python: for, while, break, continue, and Nested Loops

This article explains why loops are needed in programming, introduces Python's for‑in and while loops, demonstrates their syntax with practical examples—including range variations, break/continue statements, and nested loops such as the multiplication table—and provides exercises on prime checking and GCD/LCM calculation.

Python Programming Learning Circle
Python Programming Learning Circle
Python Programming Learning Circle
Understanding Loop Structures in Python: for, while, break, continue, and Nested Loops

When writing programs we often encounter situations that require repeating a command or a group of commands, such as continuously moving a robot toward a goal or printing "hello, world" every second for an hour; loops provide a structured way to handle these repetitions.

Python offers two primary loop constructs: the for‑in loop , suitable when the number of iterations is known, and the while loop , used when the iteration count is uncertain.

for‑in loop

If the number of iterations is predetermined, a for‑in loop is recommended, for example to compute the sum of numbers from 1 to 100:

<code>"""\n用for循环实现1~100求和\n"""
total = 0
for x in range(1, 101):
    total += x
print(total)
</code>

The range function can generate various sequences; examples include range(101) (0‑100), range(1, 101) (1‑100), range(1, 101, 2) (odd numbers), and range(100, 0, -2) (even numbers descending).

Using range(2, 101, 2) we can sum the even numbers between 1 and 100:

<code>"""\n用for循环实现1~100之间的偶数求和\n"""
total = 0
for x in range(2, 101, 2):
    total += x
print(total)
</code>

while loop

When the exact number of iterations is unknown, a while loop controls execution with a boolean expression; the loop continues while the expression evaluates to True and stops when it becomes False . An example is a "guess the number" game:

<code>"""\n猜数字游戏\n"""
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>

Keywords break and continue allow early exit from a loop or skipping the remainder of the current iteration, respectively.

Nested loops

Loops can be nested inside one another; a classic example is printing the multiplication table (九九表):

<code>"""\n打印乘法口诀表\n"""
for i in range(1, 10):
    for j in range(1, i + 1):
        print(f'{i}*{j}={i * j}', end='\t')
    print()
</code>

In this code the outer loop creates nine rows, while the inner loop generates the columns for each row.

Practice exercises

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

<code>"""\n输入一个正整数判断它是不是素数\n"""
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>"""\n输入两个正整数计算它们的最大公约数和最小公倍数\n"""
x = int(input('x = '))
y = int(input('y = '))
if x > y:
    x, y = y, x
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 branching and looping structures—using for when the iteration count is known, while when it is not, and employing break and continue for flow control—you can solve a wide range of practical problems efficiently.

Pythonprogramming fundamentalsloopsforwhile
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.