Flow of Control in Python

Flow of control determines the order in which statements are executed in a Python program. It is controlled using conditional statements, loops, and function calls.


1. Conditional Statements

Conditional statements allow a program to make decisions based on conditions.

1.1 if Statement

Executes a block of code if the condition is True.

x = 10
if x > 5:
    print("x is greater than 5")

1.2 if-else Statement

Executes one block of code if the condition is True, otherwise executes another block.

x = 10
if x % 2 == 0:
    print("Even number")
else:
    print("Odd number")

1.3 if-elif-else Statement

Used when multiple conditions need to be checked.

score = 85
if score >= 90:
    print("Grade: A")
elif score >= 80:
    print("Grade: B")
elif score >= 70:
    print("Grade: C")
else:
    print("Grade: F")

2. Looping Statements

Loops are used to execute a block of code multiple times.

2.1 for Loop

Iterates over a sequence (list, tuple, string, etc.).

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

Iterating over a list:

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

2.2 while Loop

Repeats a block of code while a condition remains True.

x = 5
while x > 0:
    print(x)
    x -= 1  # Decrement x

2.3 break and continue

  • break: Exits the loop early.
  • continue: Skips the current iteration and moves to the next one.

Example using break:

for num in range(10):
    if num == 5:
        break  # Stop loop when num is 5
    print(num)

Example using continue:

for num in range(5):
    if num == 2:
        continue  # Skip when num is 2
    print(num)

3. Nested Control Structures

Control statements can be nested inside each other.

Example: Nested if Statements

x = 10
y = 5
if x > 5:
    if y > 2:
        print("Both conditions are True")

Example: Nested Loops

for i in range(3):
    for j in range(2):
        print(f"i={i}, j={j}")

4. pass Statement

The pass statement is a placeholder used when a statement is syntactically required but no action is needed.

for i in range(5):
    if i == 3:
        pass  # Placeholder for future implementation
    print(i)

5. Summary

Conditional statements (if, if-else, if-elif-else) control decision-making.
Loops (for, while) allow repeated execution of code blocks.
break and continue modify loop execution.
Nested control structures enable complex decision-making.
pass is used as a placeholder.

Leave a Reply

Your email address will not be published. Required fields are marked *

Scroll to Top