Fading Coder

One Final Commit for the Last Sprint

Home > Tech > Content

Python Conditional and Loop Statements: if, for, while

Tech 1

Conditional Statements: if

Execute code block 'a' if condition A is met, otherwise execute code block 'b'. This control flow is called a condisional statemant.

Basic Example

age = 20
if age >= 18:
    print("Adult")
else:
    print("Minor")

Multi-Condtiion Example

score = 75
if score >= 90:
    print("Excellent")
elif score >= 80:
    print("Good")
elif score >= 70:
    print("Average")
elif score >= 60:
    print("Pass")
else:
    print("Fail")

Truthy/Falsy Values

In Python, values evaluate to:

  • False: None, empty lists/sets/dicts/tuples/strings, 0, False
  • True: Non-empty sequences, non-zero numbers, True
value = 1
if value:
    print("Valid")

Compound Conditions

# AND condition
if condition_a and condition_b:
    pass

# OR condition
if condition_a or condition_b:
    pass

# NOT condition
if not condition_a:
    pass

Loop Statements: for

Iterates over sequence items like lists or strings.

Basic Iteration

phones = ["Apple", "Huawei", "Xiaomi"]
for phone in phones:
    print(f"Current phone: {phone}")

Indexed Iteration

for index, phone in enumerate(phones):
    print(f"Phone {index + 1}: {phone}")

Loop Control

# Break example
for i in [0, 1, 2]:
    if i == 1:
        break
    print(i)

# Continue example
for i in [0, 1, 2]:
    if i == 1:
        continue
    print(i)

For-Else Structure

for i in [0, 1, 2]:
    if i == 1:
        continue
    print(i)
else:
    print("Loop completed normally")

Loop Statements: while

Repeats execution while condition remains true.

Basic While Loop

age = 1
while age <= 3:
    print(f"Age {age}: Not ready for school")
    age += 1
print("Ready for kindergarten")

Infinite Loop

while True:
    # Requires break condition
    pass

While-Else Structure

age = 1
while age <= 3:
    print(f"Current age: {age}")
    age += 1
else:
    print("Ready for school")

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

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

Leave a Comment

Anonymous

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