python
examples
examples.py🐍python
"""
03 - Control Flow: Examples
Run this file to see all control flow concepts in action!
"""
print("=" * 60)
print("CONTROL FLOW - EXAMPLES")
print("=" * 60)
# =============================================================================
# 1. IF-ELIF-ELSE STATEMENTS
# =============================================================================
print("\n--- 1. If-Elif-Else Statements ---\n")
# Basic if-else
age = 20
print(f"Age: {age}")
if age >= 18:
print("You are an adult")
else:
print("You are a minor")
# Multiple conditions with elif
print("\nGrading System:")
score = 85
print(f"Score: {score}")
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"Grade: {grade}")
# Nested if
print("\nDriving eligibility:")
age = 25
has_license = True
print(f"Age: {age}, Has License: {has_license}")
if age >= 18:
if has_license:
print("You can drive!")
else:
print("Get a license first!")
else:
print("Too young to drive")
# =============================================================================
# 2. LOGICAL OPERATORS IN CONDITIONS
# =============================================================================
print("\n--- 2. Logical Operators ---\n")
x, y = 10, 5
# AND operator
print(f"x = {x}, y = {y}")
if x > 5 and y > 3:
print("Both conditions are True (AND)")
# OR operator
if x > 100 or y > 3:
print("At least one condition is True (OR)")
# NOT operator
is_raining = False
if not is_raining:
print("It's not raining, let's go outside!")
# Complex conditions
age = 25
has_id = True
is_vip = False
if (age >= 21 and has_id) or is_vip:
print("Access granted to VIP lounge")
# =============================================================================
# 3. TERNARY OPERATOR
# =============================================================================
print("\n--- 3. Ternary Operator ---\n")
# Simple ternary
age = 20
status = "adult" if age >= 18 else "minor"
print(f"Age {age}: {status}")
# Ternary with numbers
x = 10
result = "positive" if x > 0 else "zero or negative"
print(f"Number {x} is {result}")
# Nested ternary (use sparingly!)
score = 75
grade = "A" if score >= 90 else "B" if score >= 80 else "C" if score >= 70 else "F"
print(f"Score {score} = Grade {grade}")
# =============================================================================
# 4. TRUTHY AND FALSY VALUES
# =============================================================================
print("\n--- 4. Truthy and Falsy Values ---\n")
# Falsy values
falsy_values = [False, None, 0, 0.0, "", [], {}, (), set()]
print("Falsy values:")
for val in falsy_values:
if not val:
print(f" {repr(val):15} is Falsy")
# Truthy values
truthy_values = [True, 1, -1, 0.1, "hello", [1], {"a": 1}, (1,)]
print("\nTruthy values:")
for val in truthy_values:
if val:
print(f" {repr(val):15} is Truthy")
# Practical use
items = []
print(f"\nChecking list {items}:")
if items:
print("List has items")
else:
print("List is empty")
items = [1, 2, 3]
print(f"Checking list {items}:")
if items:
print("List has items")
else:
print("List is empty")
# =============================================================================
# 5. FOR LOOPS
# =============================================================================
print("\n--- 5. For Loops ---\n")
# Iterate over list
print("Iterating over list:")
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(f" {fruit}")
# Iterate over string
print("\nIterating over string 'Python':")
for char in "Python":
print(f" {char}", end=" ")
print()
# range() function
print("\nrange(5):", end=" ")
for i in range(5):
print(i, end=" ")
print()
print("range(1, 6):", end=" ")
for i in range(1, 6):
print(i, end=" ")
print()
print("range(0, 10, 2):", end=" ")
for i in range(0, 10, 2):
print(i, end=" ")
print()
print("range(5, 0, -1):", end=" ")
for i in range(5, 0, -1):
print(i, end=" ")
print()
# =============================================================================
# 6. ENUMERATE AND ZIP
# =============================================================================
print("\n--- 6. Enumerate and Zip ---\n")
# enumerate - get index and value
fruits = ["apple", "banana", "cherry"]
print("enumerate():")
for index, fruit in enumerate(fruits):
print(f" {index}: {fruit}")
print("\nenumerate(start=1):")
for index, fruit in enumerate(fruits, start=1):
print(f" {index}: {fruit}")
# zip - iterate multiple sequences
names = ["Alice", "Bob", "Charlie"]
ages = [25, 30, 35]
cities = ["NYC", "LA", "Chicago"]
print("\nzip() with two lists:")
for name, age in zip(names, ages):
print(f" {name} is {age} years old")
print("\nzip() with three lists:")
for name, age, city in zip(names, ages, cities):
print(f" {name}, {age}, from {city}")
# =============================================================================
# 7. WHILE LOOPS
# =============================================================================
print("\n--- 7. While Loops ---\n")
# Basic while loop
print("Count from 0 to 4:")
count = 0
while count < 5:
print(f" {count}")
count += 1
# While with condition
print("\nCountdown:")
n = 5
while n > 0:
print(f" {n}...")
n -= 1
print(" Liftoff! 🚀")
# While with else
print("\nWhile with else:")
count = 0
while count < 3:
print(f" Count: {count}")
count += 1
else:
print(" Loop completed normally!")
# =============================================================================
# 8. BREAK AND CONTINUE
# =============================================================================
print("\n--- 8. Break and Continue ---\n")
# break - exit loop
print("break example (find first even):")
for num in range(1, 10):
if num % 2 == 0:
print(f" First even number: {num}")
break
print(f" Checking {num}...")
# continue - skip iteration
print("\ncontinue example (skip evens):")
for num in range(1, 6):
if num % 2 == 0:
continue
print(f" Odd number: {num}")
# break with else
print("\nbreak with else (else won't run if break executes):")
for num in range(1, 5):
if num == 3:
print(f" Found 3, breaking!")
break
else:
print(" Loop completed (this won't print)")
# =============================================================================
# 9. NESTED LOOPS
# =============================================================================
print("\n--- 9. Nested Loops ---\n")
# Multiplication table
print("Multiplication table (1-3):")
for i in range(1, 4):
for j in range(1, 4):
print(f" {i} x {j} = {i*j}")
print()
# Pattern printing
print("Triangle pattern:")
for i in range(1, 6):
print(" " + "*" * i)
# =============================================================================
# 10. LIST COMPREHENSIONS
# =============================================================================
print("\n--- 10. List Comprehensions ---\n")
# Basic list comprehension
squares = [x ** 2 for x in range(5)]
print(f"Squares: {squares}")
# With condition
evens = [x for x in range(10) if x % 2 == 0]
print(f"Even numbers: {evens}")
# Transform with condition
words = ["hello", "world", "python", "hi"]
long_upper = [w.upper() for w in words if len(w) > 3]
print(f"Long words uppercase: {long_upper}")
# With if-else
numbers = [1, 2, 3, 4, 5]
labels = ["even" if n % 2 == 0 else "odd" for n in numbers]
print(f"Labels: {labels}")
# Nested list comprehension
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
flat = [num for row in matrix for num in row]
print(f"Flattened matrix: {flat}")
# =============================================================================
# 11. DICTIONARY AND SET COMPREHENSIONS
# =============================================================================
print("\n--- 11. Dict and Set Comprehensions ---\n")
# Dictionary comprehension
squares_dict = {x: x**2 for x in range(5)}
print(f"Squares dict: {squares_dict}")
# From two lists
names = ["a", "b", "c"]
values = [1, 2, 3]
combined = {k: v for k, v in zip(names, values)}
print(f"Combined dict: {combined}")
# Set comprehension
nums = [1, 2, 2, 3, 3, 3]
unique_squares = {x**2 for x in nums}
print(f"Unique squares set: {unique_squares}")
# =============================================================================
# 12. PRACTICAL EXAMPLES
# =============================================================================
print("\n--- 12. Practical Examples ---\n")
# Example 1: Find prime numbers
def is_prime(n):
if n < 2:
return False
for i in range(2, int(n ** 0.5) + 1):
if n % i == 0:
return False
return True
primes = [n for n in range(2, 30) if is_prime(n)]
print(f"Primes up to 30: {primes}")
# Example 2: FizzBuzz
print("\nFizzBuzz (1-15):")
for i in range(1, 16):
if i % 3 == 0 and i % 5 == 0:
print(" FizzBuzz")
elif i % 3 == 0:
print(" Fizz")
elif i % 5 == 0:
print(" Buzz")
else:
print(f" {i}")
# Example 3: Menu system
print("\nMenu System (simulated):")
menu_options = {1: "Start", 2: "Options", 3: "Exit"}
for key, value in menu_options.items():
print(f" {key}. {value}")
# Simulating choice
choice = 2
match choice:
case 1:
print(" > Starting...")
case 2:
print(" > Opening options...")
case 3:
print(" > Goodbye!")
case _:
print(" > Invalid choice")
# Example 4: Password strength checker
def check_password_strength(password):
strength = 0
if len(password) >= 8:
strength += 1
if any(c.isupper() for c in password):
strength += 1
if any(c.islower() for c in password):
strength += 1
if any(c.isdigit() for c in password):
strength += 1
if any(c in "!@#$%^&*" for c in password):
strength += 1
return strength
passwords = ["weak", "Medium1", "Strong@123"]
print("\nPassword Strength:")
for pwd in passwords:
score = check_password_strength(pwd)
print(f" '{pwd}': {score}/5 stars")
print("\n" + "=" * 60)
print("END OF EXAMPLES")
print("=" * 60)