Skip to content

Python Conditional and Loop Statements

Conditional statements and loop statements are core control flow tools in programming. They allow your program to execute different code paths based on different conditions, or repeat execution of a segment of code, thereby implementing complex logic.

Conditional Statements

Conditional statements are used to decide which code block to execute based on whether a certain condition is true.

if Statement

If the condition is True, execute the code block below if.

python
age = 18
if age >= 18:
    print("You are an adult.")

if...else Statement

If the condition is True, execute the if block; otherwise, execute the else block.

python
score = 85
if score >= 60:
    print("You passed exam.")
else:
    print("You failed exam.")

if...elif...else Statement

When you need to check multiple conditions, you can use an elif (else if) chain.

python
score = 88

if score >= 90:
    print("Grade: A")
elif score >= 80:
    print("Grade: B")
elif score >= 70:
    print("Grade: C")
elif score >= 60:
    print("Grade: D")
else:
    print("Grade: F")
# Output: Grade: B

Loop Statements

Loop statements are used to repeatedly execute a segment of code.

for Loop

for loops are used to iterate over any iterable object (such as lists, tuples, strings, dictionaries, sets, or range objects).

Iterating over a list:

python
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
    print(fruit)

Using range() function: The range() function can generate a numeric sequence, often used to control the number of loop iterations.

python
# Print 0 to 4
for i in range(5):
    print(i) # Output 0, 1, 2, 3, 4

# Print 2 to 5
for i in range(2, 6):
    print(i) # Output 2, 3, 4, 5

while Loop

The while loop continues executing its code block as long as the specified condition is True. You need to ensure there is code inside the loop that can eventually make the condition False; otherwise, it will result in an infinite loop.

python
count = 0
while count < 5:
    print(f"Count is: {count}")
    count = count + 1 # Update loop variable to avoid infinite loop

Loop Control Statements

Sometimes you need to change the normal execution flow within a loop.

break Statement

break is used to immediately terminate the entire loop and execute code after the loop.

python
for i in range(10):
    if i == 5:
        break  # When i equals 5, exit the loop
    print(i)
# Output: 0, 1, 2, 3, 4

continue Statement

continue is used to skip the remainder of the current loop iteration and go directly to the next iteration.

python
for i in range(10):
    if i % 2 == 0: # If i is even
        continue   # Skip the print statement of this loop
    print(i)
# Output: 1, 3, 5, 7, 9

else Clause

Python's loops have an uncommon feature: they can have an else clause. This else block executes only when the loop completes normally (i.e., not interrupted by a break statement).

python
for i in range(5):
    print(i)
else:
    print("The loop finished normally.")

# If the loop is interrupted by break, the else block won't execute
for i in range(5):
    if i == 3:
        break
    print(i)
else:
    print("This will not be printed.")

Content is for learning and research only.