This tutorial will guide you through Python’s control structures, including conditionals, loops, and exception handling. You’ll learn how to write efficient, readable, and maintainable code by mastering these fundamental concepts. Each step builds on the previous one, with practical examples and engaging exercises to solidify your understanding.
Step 1: Understanding Conditional Statements
Conditional statements allow your program to make decisions based on certain conditions. In Python, the primary conditional statements are if, elif, and else. These statements evaluate a condition and execute a block of code if the condition is true.
# Example: Checking if a number is positive, negative, or zero
num = 5
if num > 0:
print('Positive')
elif num < 0:
print('Negative')
else:
print('Zero')Practice Exercise
Write a program that checks if a user-inputted number is even or odd. If the number is even, print 'Even'. If it's odd, print 'Odd'.
Show Solution
# Solution
def check_even_odd():
num = int(input('Enter a number: '))
if num % 2 == 0:
print('Even')
else:
print('Odd')
check_even_odd()Step 2: Working with Nested Conditionals
Nested conditionals are if statements inside other if statements. They allow you to handle more complex decision-making scenarios. However, excessive nesting can make your code harder to read, so use them judiciously.
# Example: Checking if a number is positive and even
num = 6
if num > 0:
if num % 2 == 0:
print('Positive and Even')
else:
print('Positive and Odd')
else:
print('Non-positive')Practice Exercise
Write a program that checks if a user-inputted year is a leap year. A leap year is divisible by 4 but not by 100, unless it's also divisible by 400.
Show Solution
# Solution
def is_leap_year(year):
if (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0):
return True
else:
return False
print(is_leap_year(2000)) # Output: TrueStep 3: Introduction to Loops: `for` and `while`
Loops allow you to repeat a block of code multiple times. Python provides two types of loops: for loops (for iterating over sequences) and while loops (for repeating code while a condition is true).
# Example: Using a for loop to print numbers from 1 to 5
for i in range(1, 6):
print(i)
# Example: Using a while loop to print numbers from 1 to 5
count = 1
while count <= 5:
print(count)
count += 1Practice Exercise
Write a program that calculates the factorial of a number using a while loop. The factorial of a number n is the product of all positive integers less than or equal to n.
Show Solution
# Solution
def factorial(n):
result = 1
while n > 1:
result *= n
n -= 1
return result
print(factorial(5)) # Output: 120Step 4: Loop Control: `break`, `continue`, and `else`
Python provides tools to control the flow of loops. break exits the loop entirely, continue skips the rest of the current iteration, and else executes a block of code when the loop finishes normally (i.e., without a break).
# Example: Using break to exit a loop early
for i in range(10):
if i == 5:
break
print(i)
# Example: Using continue to skip even numbers
for i in range(10):
if i % 2 == 0:
continue
print(i)
# Example: Using else with a loop
for i in range(3):
print(i)
else:
print('Loop finished')Practice Exercise
Write a program that finds the first prime number greater than 50 using a while loop and break. A prime number is only divisible by 1 and itself.
Show Solution
# Solution
def is_prime(n):
if n <= 1:
return False
for i in range(2, int(n**0.5) + 1):
if n % i == 0:
return False
return True
num = 51
while True:
if is_prime(num):
print(f'First prime greater than 50: {num}')
break
num += 1Step 5: Exception Handling with `try`, `except`, and `finally`
Exception handling allows you to manage errors gracefully. Use try to wrap code that might raise an exception, except to handle specific exceptions, and finally to execute code regardless of whether an exception occurred.
# Example: Handling division by zero
try:
result = 10 / 0
except ZeroDivisionError:
print('Cannot divide by zero!')
finally:
print('Execution complete.')Practice Exercise
Write a program that asks the user for two numbers and divides them. Handle potential exceptions like division by zero or invalid input (e.g., non-numeric values).
Show Solution
# Solution
def divide_numbers():
try:
num1 = float(input('Enter the first number: '))
num2 = float(input('Enter the second number: '))
result = num1 / num2
print(f'Result: {result}')
except ZeroDivisionError:
print('Error: Cannot divide by zero.')
except ValueError:
print('Error: Invalid input. Please enter numeric values.')
finally:
print('Operation complete.')
divide_numbers()Step 6: Combining Control Structures
In real-world applications, you'll often combine control structures to solve complex problems. For example, you might use loops inside conditionals or handle exceptions within loops.
# Example: Finding prime numbers in a range using nested loops
for num in range(2, 20):
is_prime = True
for i in range(2, int(num**0.5) + 1):
if num % i == 0:
is_prime = False
break
if is_prime:
print(f'{num} is prime')Practice Exercise
Write a program that simulates a simple ATM. The user can deposit, withdraw, or check their balance. Use loops, conditionals, and exception handling to ensure the program runs smoothly.
Show Solution
# Solution
balance = 1000
while True:
print('\n1. Deposit\n2. Withdraw\n3. Check Balance\n4. Exit')
choice = input('Enter your choice: ')
try:
if choice == '1':
amount = float(input('Enter deposit amount: '))
balance += amount
print(f'New balance: {balance}')
elif choice == '2':
amount = float(input('Enter withdrawal amount: '))
if amount > balance:
print('Insufficient funds!')
else:
balance -= amount
print(f'New balance: {balance}')
elif choice == '3':
print(f'Current balance: {balance}')
elif choice == '4':
print('Exiting...')
break
else:
print('Invalid choice. Please try again.')
except ValueError:
print('Invalid input. Please enter a numeric value.')Sign in to take Cornell notes on this lesson — they save automatically and stay with your account.