Mastering Loops in Python: For-In and While Made Simple

Application Scenarios

When writting programs, you often need to execute certain instructions repeatedly. For instance, in a robot soccer game, if the robot has the ball but is not yet within shooting range, you must keep issuing commands to move towards the goal. Here, moving towards the goal is a repeated action, and you also need conditional structures to check if the robot has the ball and is within range. Another simple example: to print "hello, world" every second for an hour, you wouldn't write print('hello, world') 3600 times; instead, you use loops.

Loops are structures that control the repeated execution of instructions. Python offers two types: for-in loops and while loops.

For-In Loops

When the number of iterations is known, for-in is recommended. For example, summing numbers from 1 to 100. The block controlled by the loop is indented, similar to conditionals. See the example below:

"""
Sum 1 to 100 using for loop
"""
total = 0
for x in range(1, 101):
    total += x
print(total)

range(1, 101) creates a sequence from 1 to 100. The loop variable x takes each integer in that range. range is flexible:

  • range(101) generates integers 0 to 100 (excluding 101).
  • range(1, 101) generates 1 to 100.
  • range(1, 101, 2) generates odd numbers from 1 too 100 (step=2).
  • range(100, 0, -2) generates even numbers from 100 down to 2 (step=-2).

To sum even numbers between 1 and 100:

"""
Sum even numbers from 1 to 100
"""
total = 0
for x in range(2, 101, 2):
    total += x
print(total)

While Loops

When the iteration count is unknown, use while. It continues as long as its condition evaluates to True. Here's a "guess the number" game:

"""
Guess the number game
"""
import random

answer = random.randint(1, 100)
counter = 0
while True:
    counter += 1
    number = int(input('Enter your guess: '))
    if number < answer:
        print('Higher')
    elif number > answer:
        print('Lower')
    else:
        print('Congratulations! You guessed it.')
        break
print(f'You guessed {counter} times.')

Here, while True creates an infinite loop, and break exits when the guess is correct. continue skips the rest of the current iteration and moves to the next.

Nested Loops

Loops can be nested, like in this multiplication table (1 to 9):

"""
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()

The outer loop produces 9 rows; the inner loop controls columns per row. After each inner loop, print() creates a new line.

Examples

Example 1: Check if a positive integer is prime.

"""
Check if a number is prime
"""
num = int(input('Enter a positive integer: '))
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} is prime')
else:
    print(f'{num} is not prime')

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

"""
Compute GCD and LCM
"""
x = int(input('x = '))
y = int(input('y = '))
if x > y:
    x, y = y, x  # swap values
for factor in range(x, 0, -1):
    if x % factor == 0 and y % factor == 0:
        print(f'GCD of {x} and {y} is {factor}')
        print(f'LCM of {x} and {y} is {x * y // factor}')
        break

Summary

With bracnhes and loops, you can solve many real-world problems. Use for when you know the iteration count; use while when it's indefinite. break exits a loop prematurely, and continue skips to the next iteration.

Tags: python loops for loop While Loop programming

Posted on Sat, 26 Sep 2026 16:14:34 +0000 by eurozaf