Fading Coder

One Final Commit for the Last Sprint

Home > Tech > Content

Loop Structures in Python

Tech 2

I. Classification of Loops

  • while loop
  • for-in traversal loop

II. The while Loop

1. Syntax of while

while condition:
    # loop body

2. Difference Between if and while

  • if evaluates the condition once; if true, executes the block once.
  • while evaluates the condition n+1 times; if true, executes the block n times.

Example:

print('Using if')
a = 1
if a < 10:
    print(a)
    a += 1

print('Using while')
a = 1
while a < 10:
    print(a, end=" ")
    a += 1

Output:

while vs if

3. Execution Flow (Example: Sum of Numbers 0 to 4)

  1. Initialize variables: sum = 0, a = 0
  2. Condition check: while a < 5:
  3. Execute loop body: sum += a
  4. Update variable: a += 1
  5. Print result: print('Sum:', sum)

Tip: The variable used for initialization, condition check, and update must be the same.

4. Example: Sum of Even Numbers from 1 to 100

total = 0
num = 1
while num <= 100:
    if num % 2 == 0:
        total += num
    num += 1
print('Sum of even numbers from 1 to 100:', total)

Important: The increment statement num += 1 must be at the same indentation level as the if statement, not inside it. If placed inside the if, odd values of num would never increment, causing an infinite loop.

Alternatively, the evenness check can be written as:

if not bool(num % 2):

Becuase 0 evaluatse to False, and not False is True.

III. The for-in Loop

1. Syntax of for-in

for variable in iterable:
    # loop body

Tip: in sequentially takes values fromm an iterable (e.g., strings, sequences). Iterable objects in Python include strings, lists, tuples, dictionaries, sets, etc.

2. Example

for i in range(10):
    print(i, end=" ")

Output:

for range output

range() generates a sequence of integers, which is also an iterable.

3. Using Underscore for Unused Variable

If the loop variable is not needed, use an underscore _:

for _ in range(5):
    print('Life is short, I use Python')

Output:

underscore loop

4. Common Exercise Examples

(1) Sum of Even Numbers from 1 to 100 using for

total = 0
for num in range(1, 101):
    if num % 2 == 0:
        total += num
print('Sum of even numbers from 1 to 100:', total)

(2) Find Armstrong Numbers (Narcissistic Numbers) between 100 and 999

An Armstrong number is one where the sum of the cubes of its digits equals the number itself.

for num in range(100, 1000):
    units = num % 10
    tens = (num // 10) % 10
    hundreds = num // 100
    if units**3 + tens**3 + hundreds**3 == num:
        print(num)

Related Articles

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

Implement Image Upload Functionality for Django Integrated TinyMCE Editor

Django’s Admin panel is highly user-friendly, and pairing it with TinyMCE, an effective rich text editor, simplifies content management significantly. Combining the two is particular useful for bloggi...

Comprehensive Guide to Hive SQL Syntax and Operations

This article provides a detailed walkthrough of Hive SQL, categorizing its features and syntax for practical use. Hive SQL is segmented into the following categories: DDL Statements: Operations on...

Leave a Comment

Anonymous

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