Fading Coder

One Final Commit for the Last Sprint

Home > Tech > Content

Python Loop Structures: Basics, Syntax, Control Flow, and Helper Tools

Tech 2

while Loop Fundamentals

Syntax Guidelines

While loops execute a code block repeatedly as long as a specified boolean condition evaluates to True. Key requirements include:

  • A boolean expression that resolves to True/False
  • Consistent 4-space indentation for the loop body
  • A well-defined exit condition to avoid infinite execution
# Calculate product of integers from 1 to 10
factorial_result = 1
current_num = 2
while current_num <= 10:
    factorial_result *= current_num
    current_num += 1

print(f"10! is: {factorial_result}")

Print Formatting Extras

Unbroken Output

Add end='' to the print() function to prevent automatic line breaks.

Tab Alignment

Insert \t in strings to align content horizontally, equivalent to pressing the Tab key.

for Loop Fundamentals

Syntax Overview

For loops iterate over iterable objects (like strings, lists, or range sequences) and process each element individually. Important notes:

  • No explicit boolean loop condition; iteration stops when the iterable is exhausted
  • Indentation rules apply identical to while loops
# Iterate over a greeting string and count vowels
greeting = "bonjour"
vowel_count = 0
for char in greeting:
    if char.lower() in {'a', 'e', 'i', 'o', 'u'}:
        vowel_count += 1

print(f"Vowels in '{greeting}': {vowel_count}")

range() Sequence Generator

Functionality and Syntax

range() creates a memory-efficient iterable numeric sequence, commonly used with for loops. It supports three syntax variants:

  1. range(end): Generates integers starting at 0, up to but not including end
  2. range(start, end): Generates integers starting at start, up to but not including end
  3. range(start, end, step): Generates integers with a custom interval step between values
# Iterate over even numbers from 20 down to 2
for even_val in range(20, 0, -2):
    print(even_val, end=' ')

For Loop Temporary Variable Scope

Temporary variables used in for loops are technically accessible outside the loop, but this violates Python coding conventions. To safely reference the varible after iteration, initialize it explicitly before the loop starts.

# Explicitly initialize index variable before loop
final_index = -1
for final_index in range(7):
    pass

print(f"Last loop index value: {final_index}")

Loop Control Statements

contineu and break

Both control statements modify loop execution flow and work identically in while and for loops, affecting only the innermost loop they appear in:

  • continue: Skips the remaining code in the current iteration and proceeds to the next
  • break: Terminates the entire current loop immediately
# Skip numbers divisible by 3 and stop at 17
for num in range(10, 25):
    if num == 17:
        break
    if num % 3 == 0:
        continue
    print(num, end=' | ')

Related Articles

Understanding Strong and Weak References in Java

Strong References Strong reference are the most prevalent type of object referencing in Java. When an object has a strong reference pointing to it, the garbage collector will not reclaim its memory. F...

Comprehensive Guide to SSTI Explained with Payload Bypass Techniques

Introduction Server-Side Template Injection (SSTI) is a vulnerability in web applications where user input is improper handled within the template engine and executed on the server. This exploit can r...

SBUS Signal Analysis and Communication Implementation Using STM32 with Fus Remote Controller

Overview In a recent project, I utilized the SBUS protocol with the Fus remote controller to control a vehicle's basic operations, including movement, lights, and mode switching. This article is aimed...

Leave a Comment

Anonymous

◎Feel free to join the discussion and share your thoughts.