Python Loop Structures and Control Flow

While Loops

While loops in Python allow for repeated execution of code as long as a specified condition remains true.

# Initialize countercounter = 1# Loop while condition is metwhile counter <= 10:    print(f'Day {counter}: Weather is pleasant today')    counter += 1  # Increment counter

Execution Flow:

  1. Initialize variables before the loop begins
  2. Check the condition
  3. If condition is true, execute the loop body
  4. Update variables that affect the condition
  5. Repeat steps 2-4 until condition becomes false

Practical Examples

# Example 1: Print numbers 1-100number = 1while number <= 100:    print(number)    number += 1<br># Example 2: Print even numbers between 1-100number = 1while number <= 100:    if number % 2 == 0:        print(number)    number += 1<br># Example 3: Print odd numbers between 1-100number = 1while number <= 100:    if number % 2 == 1:        print(number)    number += 1<br># Example 4: Calculate sum of numbers 1-100total = 0current = 1while current <= 100:    total += current    current += 1print(f'Sum of numbers 1-100: {total}')<br># Example 5: Calculate sum of numbers divisible by 7 between 1-100total = 0current = 1while current <= 100:    if current % 7 == 0:        total += current    current += 1print(f'Sum of numbers divisible by 7: {total}')

For Loops

For loops are used for iterating over a sequence (like a list, tuple, dictionary, set, or string) or other iterable objects.

# Syntaxfor variable in sequence:    # Code to execute for each item

Practical Examples

# Example 1: Print numbers 1-100for num in range(1, 101):    print(num)<br># Example 2: Print odd numbers between 1-100for num in range(1, 100, 2):    print(num)<br># Example 3: Calculate sum of numbers 1-100sum_result = 0for num in range(1, 101):    sum_result += numprint(f'Sum of numbers 1-100: {sum_result}')

Break Statement

The break statement terminates the current loop and transfers execution to the statement following the loop.

counter = 1while counter <= 10:    if counter == 3:        counter += 1        break  # Exit the loop    print(counter)    counter += 1

Continue Statement

The continue statement skips the rest of the current iteration and jumps to the next iteration of the loop.

counter = 1while counter <= 10:    if counter == 3:        counter += 1        continue  # Skip this iteration    print(counter)    counter += 1

Infinite Loops

An infinite loop is a loop that continues indefinitely. In Python, these are typically implemented with while True.

# Basic infinite loopwhile True:    print('This will print forever')<br># Example: User authentication with infinite loopcorrect_username = 'admin'correct_password = 'secure123'while True:    username = input('Enter username: ')    password = input('Enter password: ')    if username == correct_username and password == correct_password:        print('Login successful!')        break    else:        print('Invalid credentials. Please try again.')

Nested Loops

Loops can be nested inside other loops. Both while and for loops can be nested, and there's no strict limit to nesting depth, though performance considerations typically limit nesting to 3 levels.

For Loop Nesting

# Syntaxfor outer_variable in outer_sequence:    for inner_variable in inner_sequence:        # Code to execute

While Loop Nesting

# Syntaxouter_condition = initial_valuewhile outer_condition:    inner_condition = initial_value    while inner_condition:        # Code to execute        # Update inner_condition    # Update outer_condition

Example: Printing Patterns

# Using nested for loopsfor row in range(3):    for col in range(4):        print('*', end=' ')    print()  # New line after each row<br># Using nested while loopsrow = 1while row <= 3:    col = 1    while col <= 4:        print('*', end=' ')        col += 1    print()    row += 1

Multiplication Table

Nested loops are commonly used to generate multiplication tables.

# Using for loopsfor i in range(1, 10):    for j in range(1, i + 1):        print(f'{j} × {i} = {i*j}', end=' ')    print()<br># Using while loopsi = 1while i <= 9:    j = 1    while j <= i:        print(f'{j} × {i} = {i*j}', end=' ')        j += 1    print()    i += 1

Important Notes

  1. In nested loops, the outer loop controls rows, while the inner loop controls columns (number of items per row)
  2. Each iteration of the outer loop completes a full execution of the inner loop

Tags: python loops Control Flow programming Tutorial

Posted on Wed, 13 May 2026 23:24:07 +0000 by TheTitans