# -*- coding: utf-8 -*-
"""
================================================================================
Comprehensive Python Guide: Control Structures
================================================================================
This program provides an in-depth demonstration of Python's control flow
mechanisms. It covers conditional statements, loops, and error handling,
which are essential for building logic into your programs.
Sections:
1. Conditional Statements (if, elif, else)
2. Looping Statements (for, while)
3. Loop Control Statements (break, continue, pass)
4. Error Handling (try, except, else, finally)
"""
# A function to print section headers for better readability.
def print_header(title):
"""Prints a formatted header to the console."""
print("\n" + "="*60)
print(f"| {title.center(56)} |")
print("="*60)
# ==============================================================================
# SECTION 1: CONDITIONAL STATEMENTS (if, elif, else)
# ==============================================================================
# These statements allow you to execute code blocks based on certain conditions.
print_header("Conditional Statements")
# --- 1.1: Simple 'if' statement ---
print("\n--- 1.1: Simple 'if' statement ---")
temperature = 35
if temperature > 30:
print("It's a hot day!")
# --- 1.2: 'if-else' statement ---
print("\n--- 1.2: 'if-else' statement ---")
age = 17
if age >= 18:
print("You are eligible to vote.")
else:
print("You are not eligible to vote yet.")
# --- 1.3: 'if-elif-else' chain ---
print("\n--- 1.3: '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"A score of {score} gets you a grade of '{grade}'.")
# --- 1.4: Nested 'if' statements ---
print("\n--- 1.4: Nested 'if' statements ---")
is_citizen = True
age = 20
if is_citizen:
if age >= 18:
print("You are a citizen and eligible to vote.")
else:
print("You are a citizen but not yet old enough to vote.")
else:
print("You must be a citizen to vote.")
# --- 1.5: Ternary Operator (Conditional Expression) ---
# A concise way to write a simple if-else statement.
print("\n--- 1.5: Ternary Operator ---")
is_raining = False
weather_status = "Bring an umbrella" if is_raining else "Enjoy the sunshine"
print(f"Weather status: {weather_status}")
# ==============================================================================
# SECTION 2: LOOPING STATEMENTS (for, while)
# ==============================================================================
# Loops are used to execute a block of code repeatedly.
print_header("Looping Statements")
# --- 2.1: 'for' loop ---
# Used for iterating over a sequence (like a list, tuple, dict, set, or string).
print("\n--- 2.1: 'for' loop ---")
# Iterating over a list
print("Iterating over a list:")
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(f"- {fruit}")
# Iterating over a string
print("\nIterating over a string:")
for char in "Python":
print(char, end=" ")
print() # for a new line
# Using the range() function
print("\nIterating with range():")
for i in range(5): # from 0 up to (but not including) 5
print(f"Number: {i}")
# Using range() with start, stop, and step
print("\nIterating with range(start, stop, step):")
for i in range(2, 11, 2): # from 2 to 10, incrementing by 2
print(f"Even number: {i}")
# Iterating over dictionary keys
print("\nIterating over dictionary keys:")
my_dict = {"name": "Alice", "age": 30}
for key in my_dict:
print(f"Key: {key}, Value: {my_dict[key]}")
# Using enumerate() to get both index and value
print("\nIterating with enumerate():")
for index, fruit in enumerate(fruits):
print(f"Fruit at index {index} is {fruit}")
# --- 2.2: 'while' loop ---
# Repeats a block of code as long as a condition is true.
print("\n--- 2.2: 'while' loop ---")
count = 5
print("Countdown:")
while count > 0:
print(count)
count -= 1 # Decrement the counter
print("Blast off!")
# ==============================================================================
# SECTION 3: LOOP CONTROL STATEMENTS (break, continue, pass)
# ==============================================================================
print_header("Loop Control Statements")
# --- 3.1: 'break' statement ---
# Exits the loop immediately.
print("\n--- 3.1: 'break' statement ---")
print("Finding the number 7 in a list:")
numbers = [1, 5, 12, 7, 9, 20]
for num in numbers:
print(f"Checking {num}...")
if num == 7:
print("Found it! Breaking the loop.")
break # Exit the loop
print("Loop finished.")
# --- 3.2: 'continue' statement ---
# Skips the rest of the current iteration and moves to the next one.
print("\n--- 3.2: 'continue' statement ---")
print("Printing only even numbers from 1 to 10:")
for i in range(1, 11):
if i % 2 != 0: # If the number is odd
continue # Skip this iteration
print(f"Even number: {i}")
# --- 3.3: 'pass' statement ---
# Acts as a placeholder. It does nothing.
print("\n--- 3.3: 'pass' statement ---")
# Useful when a statement is required syntactically but you don't want any code to execute.
for i in range(3):
# TODO: Implement this feature later
pass # Avoids an IndentationError
print("The 'pass' statement did nothing, as intended.")
# --- 3.4: 'else' clause in loops ---
# The 'else' block executes only if the loop completes normally (i.e., not terminated by a 'break').
print("\n--- 3.4: 'else' clause in loops ---")
print("Searching for a number not in the list:")
for num in [1, 3, 5]:
if num == 4:
print("Found 4!")
break
else: # This will execute because the loop did not break
print("The number 4 was not found in the list.")
# ==============================================================================
# SECTION 4: ERROR HANDLING (try, except, else, finally)
# ==============================================================================
# Gracefully handles errors and exceptions that might occur during execution.
print_header("Error Handling")
# --- 4.1: Basic 'try-except' block ---
print("\n--- 4.1: Basic 'try-except' block ---")
try:
result = 10 / 0
print(f"Result is {result}")
except ZeroDivisionError:
print("Error: Cannot divide by zero!")
# --- 4.2: Handling multiple specific exceptions ---
print("\n--- 4.2: Handling multiple exceptions ---")
try:
# Change the value of 'x' to see different outcomes:
# x = "hello" # -> will trigger TypeError
# x = 10 # -> will trigger ValueError (can't convert int to int with base)
x = "10" # -> will succeed
num = int(x)
print(f"Successfully converted '{x}' to the number {num}.")
except ValueError:
print(f"Error: Could not convert '{x}' to an integer.")
except TypeError:
print(f"Error: The input '{x}' is of the wrong type for conversion.")
# --- 4.3: 'else' and 'finally' clauses ---
print("\n--- 4.3: 'else' and 'finally' clauses ---")
try:
user_input = "5" # Try changing to "abc" or "0"
number = int(user_input)
result = 100 / number
except ValueError:
print("Invalid input: Please enter a number.")
except ZeroDivisionError:
print("Error: Cannot divide by zero.")
else:
# This block runs ONLY if the 'try' block completes without any exceptions.
print(f"The result of 100 / {number} is {result}.")
finally:
# This block ALWAYS runs, regardless of whether an exception occurred or not.
print("Execution of the try-except block is complete.")
print("\n" + "="*60)
print("DEMONSTRATION COMPLETE".center(60))
print("="*60)