Control Flow in Python: If-Else Statements and Loops

Control flow structures in Python allow you to dictate the order in which your code is executed. Two fundamental constructs for control flow are if-else statements for decision-making and loops for repetitive tasks.

1. If-Else Statements:

Purpose: If-else statements are used to make decisions in your code. They allow you to execute different blocks of code based on whether a certain condition is true or false.

Syntax:

if condition: # Code to execute if the condition is true else: # Code to execute if the condition is false

Example:

age = 20

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

In this example, the program checks if the variable age is greater than or equal to 18. If true, it prints "You are an adult"; otherwise, it prints "You are a minor."

2. Loops:

Purpose: Loops allow you to repeat a block of code multiple times, saving you from writing the same code over and over.

a. For Loop:

Syntax:

for variable in iterable: # Code to execute in each iteration

Example:

fruits = ["apple", "orange", "banana"]

for fruit in fruits:
    print(fruit)

This loop iterates over the elements in the fruits list, printing each one. Output:
apple orange banana

b. While Loop:

Syntax:

while condition: # Code to execute as long as the condition is true

Example:

count = 0

while count < 5:
    print(count)
    count += 1

This loop prints the values of count from 0 to 4. Output:
0 1 2 3 4

Combining Control Flow Structures:

You can also combine if-else statements and loops for a more complex control flow. For example:

numbers = [1, 2, 3, 4, 5] for num in numbers: if num % 2 == 0: print(f"{num} is even.") else: print(f"{num} is odd.")

This loop goes through the numbers list, checks if each number is even or odd, and prints the result.

Understanding control flow is essential for creating dynamic and responsive programs. Whether making decisions with if-else statements or repeating tasks with loops, these structures empower you to create flexible and powerful Python programs.







Comments