Python Control Flow: if, elif, else, for & while Loops Explained

1. What are if, if-else, and if-elif-else statements in Python?

Q: What are conditional statements?

if: Executes a block of code if a condition is True.

if-else: Executes one block if the condition is True, another if False.

if-elif-else: Tests multiple conditions sequentially, executing the first True block or the else block if none are True.

Syntax:

if condition:
    # code block
elif condition2:  # Optional, multiple elifs allowed
    # code block
else:  # Optional
    # code block
      

Use Case: Decision-making based on conditions (e.g., grading system, user role checks).

2. Can you give an example of if, if-else, and if-elif-else?

# if, if-else, if-elif-else example
score = int(input("Enter your score (0-100): "))

# Simple if
if score >= 50:
    print("You passed!")

# if-else
if score >= 50:
    print("You passed the exam.")
else:
    print("You failed the exam.")

# if-elif-else
if score >= 90:
    grade = "A"
elif score >= 80:
    grade = "B"
elif score >= 70:
    grade = "C"
elif score >= 50:
    grade = "D"
else:
    grade = "F"
print(f"Your grade is: {grade}")
      

Output (Sample):

Enter your score (0-100): 85
You passed!
You passed the exam.
Your grade is: B
      

3. What are while and for loops in Python?

Q: What are loops in Python?

while Loop: Repeats a block of code as long as a condition is True.

Syntax:

while condition:
    # code block
      

Use Case: Repeating until a condition changes (e.g., user input loop).

for Loop: Iterates over a sequence (list, tuple, string, range, etc.).

Syntax:

for variable in sequence:
    # code block
      

Use Case: Processing items in a collection (e.g., summing numbers).

4. Can you give an example of while and for loops?

# while and for loop example
# while loop: Sum numbers until user enters 0
total = 0
while True:
    num = int(input("Enter a number (0 to stop): "))
    if num == 0:
        break
    total += num
print(f"Sum of numbers: {total}")

# for loop: Iterate over a list
fruits = ["apple", "banana", "orange"]
for fruit in fruits:
    print(f"Fruit: {fruit}")

# for loop with range
for i in range(1, 5):  # 1 to 4
    print(f"Square of {i}: {i ** 2}")
      

Output (Sample):

Enter a number (0 to stop): 5
Enter a number (0 to stop): 10
Enter a number (0 to stop): 0
Sum of numbers: 15
Fruit: apple
Fruit: banana
Fruit: orange
Square of 1: 1
Square of 2: 4
Square of 3: 9
Square of 4: 16
      

5. What are break, continue, and pass in Python?

Q: What do break, continue, and pass do?

break: Exits the nearest enclosing loop (while or for) immediately.

continue: Skips the rest of the current loop iteration and moves to the next.

pass: A no-op placeholder that does nothing; used when syntax requires a statement but no action is needed.

Use Case:

6. Can you give an example of break, continue, and pass?

# break, continue, pass example
# break: Stop when a negative number is entered
numbers = []
while True:
    num = int(input("Enter a number (negative to stop): "))
    if num < 0:
        break
    numbers.append(num)
print(f"Entered numbers: {numbers}")

# continue: Skip odd numbers
for i in range(1, 10):
    if i % 2 != 0:  # Odd numbers
        continue
    print(f"Even number: {i}")

# pass: Placeholder for future implementation
def calculate_bonus(salary):
    pass  # To be implemented later
print("Bonus function not yet implemented:", calculate_bonus(50000))
      

Output (Sample):

Enter a number (negative to stop): 4
Enter a number (negative to stop): 7
Enter a number (negative to stop): -1
Entered numbers: [4, 7]
Even number: 2
Even number: 4
Even number: 6
Even number: 8
Bonus function not yet implemented: None
      

7. What are best practices for Python control flow?

Q: What are best practices?

if Statements:

Loops:

break/continue/pass:

General: