Control Flow in Python

Control flow refers to the order in which statements are executed in a program. Python provides several constructs for controlling the flow of execution, including conditional statements and loops.

1. Conditional Statements:

Conditional statements allow you to make decisions in your code based on certain conditions.

1.1 if Statement:

The if statement is used for basic decision-making.

# Example of if statement
age = 20

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

1.2 if-else Statement:

The if-else statement allows you to execute different blocks of code based on the condition.

# Example of if-else statement
age = 15

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

1.3 if-elif-else Statement:

The if-elif-else statement is used when you have multiple conditions to check.

# Example of if-elif-else statement
score = 85

if score >= 90:
    grade = 'A'
elif score >= 80:
    grade = 'B'
    grade = 'C'

print("Your grade is:", grade)

2. Loops:

Loops allow you to repeatedly execute a block of code.

2.1 for Loop:

The for loop is used for iterating over a sequence (such as a list, tuple, or string).

# Example of for loop
fruits = ["apple", "banana", "orange"]

for fruit in fruits:

2.2 while Loop:

The while loop is used for executing a block of code as long as a specified condition is true.

# Example of while loop
counter = 0

while counter < 5:
    counter += 1

2.3 Loop Control Statements:

Python provides loop control statements like break and continue to modify the execution of loops.

# Example of break and continue
for i in range(10):
    if i == 5:
        break  # Exit the loop when i is 5
    elif i % 2 == 0:
        continue  # Skip even numbers


3. Exception Handling:

Exception handling allows you to gracefully handle errors in your code.

# Example of try-except block
    num1 = int(input("Enter a number: "))
    num2 = int(input("Enter another number: "))
    result = num1 / num2
    print("Result:", result)

except ZeroDivisionError:
    print("Error: Cannot divide by zero.")

except ValueError:
    print("Error: Invalid input. Please enter a number.")

4. Conclusion:

Understanding control flow is essential for writing effective and flexible Python programs. With conditional statements, loops, and exception handling, you have the tools to create dynamic and responsive code that can adapt to different situations.

In the next sections, we’ll explore more advanced topics and practical applications of control flow in Python.