Control Structures

Python Control Structures

Control Structures in Python

Control structures are programming constructs that allow you to control the flow of your program's execution. They enable you to make decisions, repeat actions, and organize your code into logical blocks.

1. Conditional Statements

Conditional statements allow your program to make decisions based on certain conditions.

If-Else Statements

The if-else statement is the most common type of conditional statement.

Syntax:

if condition:
    # code to execute if condition is True
elif another_condition:
    # code to execute if another_condition is True
else:
    # code to execute if all conditions are False

Examples:

  1. Basic if-else:
age = 20

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

# Output: You are an adult.
  1. If-elif-else chain:
score = 85

if score >= 90:
    grade = "A"
elif score >= 80:
    grade = "B"
elif score >= 70:
    grade = "C"
elif score >= 60:
    grade = "D"
else:
    grade = "F"

print(f"Your grade is: {grade}")

# Output: Your grade is: B
  1. Nested if statements:
x = 10
y = 5

if x > 0:
    if y > 0:
        print("Both x and y are positive.")
    else:
        print("x is positive, but y is not.")
else:
    print("x is not positive.")

# Output: Both x and y are positive.
  1. Ternary operator (conditional expression):
age = 20
status = "adult" if age >= 18 else "minor"
print(status)

# Output: adult

Switch-Case Equivalent in Python

Python doesn't have a built-in switch-case statement, but you can achieve similar functionality using dictionaries or if-elif chains.

Example using a dictionary:

def switch_demo(argument):
    switcher = {
        1: "January",
        2: "February",
        3: "March",
        4: "April"
    }
    return switcher.get(argument, "Invalid month")

print(switch_demo(2))  # Output: February
print(switch_demo(5))  # Output: Invalid month

2. Loops

Loops allow you to execute a block of code repeatedly.

For Loops

For loops are used to iterate over a sequence (like a list, tuple, string, or range) or other iterable objects.

Syntax:

for item in iterable:
    # code to execute for each item

Examples:

  1. Iterating over a list:
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
    print(fruit)

# Output:
# apple
# banana
# cherry
  1. Using range():
for i in range(5):
    print(i)

# Output:
# 0
# 1
# 2
# 3
# 4
  1. Enumerating a list:
fruits = ["apple", "banana", "cherry"]
for index, fruit in enumerate(fruits):
    print(f"Index {index}: {fruit}")

# Output:
# Index 0: apple
# Index 1: banana
# Index 2: cherry
  1. Nested for loops:
for i in range(1, 4):
    for j in range(1, 4):
        print(f"{i} * {j} = {i*j}")
    print()  # Print a newline after each inner loop

# Output:
# 1 * 1 = 1
# 1 * 2 = 2
# 1 * 3 = 3

# 2 * 1 = 2
# 2 * 2 = 4
# 2 * 3 = 6

# 3 * 1 = 3
# 3 * 2 = 6
# 3 * 3 = 9

While Loops

While loops execute a block of code as long as a condition is true.

Syntax:

while condition:
    # code to execute while condition is True

Examples:

  1. Basic while loop:
count = 0
while count < 5:
    print(count)
    count += 1

# Output:
# 0
# 1
# 2
# 3
# 4
  1. While loop with user input:
user_input = ""
while user_input.lower() != "quit":
    user_input = input("Enter a command (type 'quit' to exit): ")
    print(f"You entered: {user_input}")

print("Program ended.")

# Sample run:
# Enter a command (type 'quit' to exit): hello
# You entered: hello
# Enter a command (type 'quit' to exit): python
# You entered: python
# Enter a command (type 'quit' to exit): quit
# You entered: quit
# Program ended.
  1. Infinite loop with a break condition:
while True:
    number = int(input("Enter a positive number: "))
    if number <= 0:
        print("That's not a positive number. Try again.")
    else:
        print(f"You entered: {number}")
        break

print("Loop ended.")

# Sample run:
# Enter a positive number: -5
# That's not a positive number. Try again.
# Enter a positive number: 0
# That's not a positive number. Try again.
# Enter a positive number: 10
# You entered: 10
# Loop ended.

3. Break and Continue Statements

Break and continue statements allow you to control the flow of loops more precisely.

Break Statement

The break statement terminates the loop containing it. Control of the program flows to the statement immediately after the body of the loop.

Example:

for number in range(1, 10):
    if number == 5:
        break
    print(number)

print("Loop ended")

# Output:
# 1
# 2
# 3
# 4
# Loop ended

Continue Statement

The continue statement skips the rest of the code inside the loop for the current iteration only. Loop does not terminate but continues on with the next iteration.

Example:

for number in range(1, 6):
    if number == 3:
        continue
    print(number)

# Output:
# 1
# 2
# 4
# 5

Using Break and Continue in While Loops

Example:

count = 0
while True:
    count += 1
    if count == 3:
        continue
    if count == 5:
        break
    print(count)

print("Loop ended")

# Output:
# 1
# 2
# 4
# Loop ended

Else Clause in Loops

Python allows the use of else clauses with both for and while loops. The else block is executed when the loop condition becomes false.

Example with for loop:

for i in range(5):
    print(i)
else:
    print("Loop completed normally")

# Output:
# 0
# 1
# 2
# 3
# 4
# Loop completed normally

Example with while loop and break:

n = 0
while n < 5:
    if n == 3:
        break
    print(n)
    n += 1
else:
    print("Loop completed normally")

print("Outside the loop")

# Output:
# 0
# 1
# 2
# Outside the loop

Note that in the second example, the else block is not executed because the loop was terminated by a break statement.

These control structures form the backbone of program flow in Python. Understanding and effectively using them will greatly enhance your ability to write complex and efficient Python programs. Remember to practice these concepts with your own examples to reinforce your learning!

Summary

Conditional Statements:

  • If-Else statements with examples of basic, chained, and nested conditions
  • Ternary operator for concise conditional expressions
  • Switch-case equivalent using dictionaries

Loops:

  • For loops with examples of iterating over lists, using range(), enumeration, and nested loops
  • While loops with examples of basic usage, user input handling, and infinite loops with break conditions

Break and Continue Statements:

  • Examples of using break to exit loops early
  • Examples of using continue to skip iterations
  • Demonstration of break and continue in both for and while loops

Additional Topics:

  • Else clause in loops, showing how it works with both for and while loops
  • Examples of how break affects the else clause in loops