Skip to Content
Course content

2.4 Control Flow Statements

Control flow statements in Python allow the execution of specific blocks of code based on certain conditions or repeatedly, which provides flexibility in the program's behavior. These include conditional statements (if, elif, else), loops (for, while), and control flow modifiers like break, continue, and pass.

1. Conditional Statements

Conditional statements are used to execute a block of code based on whether a condition is True or False. Python provides the if, elif, and else statements to handle conditional logic.

1.1 if Statement

The if statement is used to test a condition. If the condition is True, the block of code under it is executed.

age = 18
if age >= 18:
    print("You are an adult.")
  • In this example, if age is 18 or greater, the message "You are an adult." will be printed.

1.2 elif Statement

The elif (short for "else if") allows testing multiple conditions. It is checked only if the if condition is False.

age = 15
if age >= 18:
    print("You are an adult.")
elif age >= 13:
    print("You are a teenager.")
  • If the if condition fails, the program checks the elif condition. If age is 15, the program will print "You are a teenager."

1.3 else Statement

The else statement is used to specify a block of code that will be executed if none of the if or elif conditions are True.

age = 10
if age >= 18:
    print("You are an adult.")
else:
    print("You are not an adult.")
  • If the condition age >= 18 is False, the else block will run, printing "You are not an adult."

2. Looping Statements

Python supports two types of loops: for loops and while loops, which are used to execute a block of code multiple times.

2.1 for Loop

A for loop is used to iterate over a sequence (such as a list, tuple, or string) and execute the block of code once for each item in the sequence.

fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
    print(fruit)
  • The loop will print each fruit in the list.

2.2 while Loop

A while loop is used to repeatedly execute a block of code as long as a condition remains True.

counter = 0
while counter < 5:
    print(counter)
    counter += 1
  • This loop will print the numbers from 0 to 4 because the loop continues as long as counter is less than 5.

3. Control Flow Modifiers

Python provides additional control flow statements to alter the behavior of loops and conditionals.

3.1 break Statement

The break statement is used to exit the loop prematurely, even if the loop's condition is still True.

for i in range(10):
    if i == 5:
        break
    print(i)
  • The loop will print numbers from 0 to 4 and then exit when i equals 5 due to the break statement.

3.2 continue Statement

The continue statement is used to skip the current iteration of the loop and proceed to the next iteration.

for i in range(5):
    if i == 3:
        continue
    print(i)
  • This loop will print 0, 1, 2, and 4, skipping 3 because of the continue statement.

3.3 pass Statement

The pass statement is a placeholder that does nothing. It is typically used in situations where a statement is syntactically required but no action is needed.

for i in range(5):
    if i == 3:
        pass
    else:
        print(i)
  • The loop behaves normally but does nothing when i == 3 due to the pass statement.

4. Nested Control Flow

You can nest conditional statements or loops within each other to create more complex control flows.

4.1 Nested if Statements

x = 10
y = 5
if x > 3:
    if y < 10:
        print("Both conditions are True")
  • The inner if statement is executed only if the outer if condition is True.

4.2 Nested Loops

for i in range(3):
    for j in range(2):
        print(f"i: {i}, j: {j}")
  • This will print combinations of i and j, effectively creating a "grid" of outputs.

5. Summary of Control Flow Statements

  • if, elif, else: Used for conditional execution based on conditions.
  • for and while loops: Used for repeating actions.
  • break: Exits the loop early.
  • continue: Skips to the next iteration in the loop.
  • pass: Placeholder for a statement that does nothing.

Conclusion

Control flow statements allow Python programs to make decisions, repeat tasks, and control the flow of execution based on conditions, making them essential for creating dynamic and functional programs. Understanding and mastering these control structures is crucial for solving problems and writing efficient Python code.

Commenting is not enabled on this course.