1.
1 Programming (general)
Explanation: Programming is the process of designing and creating software by writing
instructions that a computer can follow.
# Simple hello world program
print("Hello, World!")
1.2 Programming using Python
Explanation: Python is a high-level programming language known for its simplicity and
readability.
# A Python program to calculate the sum of two numbers
num1 = 10
num2 = 5
sum = num1 + num2
print("The sum is:", sum)
1.3 Basic input and output
Explanation: Python can interact with the user through input and output.
# Taking user input
name = input("Enter your name: ")
print("Hello, " + name + "!")
1.4 Errors
Explanation: Errors in programming can occur due to syntax mistakes or logical issues.
# Example of a syntax error
print("Hello, World!" # Missing closing parenthesis
1.5 Integrated Development Environment (IDE)
Explanation: An IDE helps write, debug, and test code more easily. Examples include
PyCharm, VSCode, and IDLE.
# In your IDE, you would write Python code in a file like `example.py` and run it.
1.6 Computers and Programs (general)
Explanation: A computer is a machine that executes programs. Programs are sequences of
instructions for the computer to follow.
# Program to demonstrate the basics of running Python code
print("Computers run programs, and this is a Python program!")
1.7 Computer tour
Explanation: A basic understanding of computer components like the CPU, RAM, and hard
drive is useful for understanding how programs run.
1.8 Language history
Explanation: Python was created by Guido van Rossum in 1989, and was released in 1991. It
was designed to emphasize code readability.
1.9 Why whitespace matters
Explanation: Python uses indentation to define blocks of code instead of braces {}.
if True:
print("This is indented correctly!")
1.10 Python example: Salary calculation
# Program to calculate salary after a 10% deduction
salary = float(input("Enter your salary: "))
deduction = salary * 0.10
final_salary = salary - deduction
print("Your final salary after 10% deduction is:", final_salary)
1.11 Additional practice: Output art
# Simple ASCII art output
print(" * ")
print(" *** ")
print("*****")
2.1 Variables and assignments
# Assigning values to variables
x=5
y = 10
z=x+y
print(z)
2.2 Identifiers
# Valid identifiers
my_variable = 10
variable1 = 20
# Invalid identifiers
# 1st_variable = 30 # Starts with a number
2.3 Objects
# In Python, everything is an object
a = 10 # Integer object
b = "Hello" # String object
2.4 Numeric types: Floating-point
# Float type
pi = 3.14159
print(type(pi))
2.5 Arithmetic expressions
# Simple arithmetic operations
a = 10
b=3
print(a + b)
print(a - b)
print(a * b)
print(a / b)
2.6 Python expressions
# Expression examples
result = (10 + 2) * 3
print(result)
2.7 Division and modulo
# Division and modulo
a = 10
b=3
print(a // b) # Integer division
print(a % b) # Modulo
2.8 Module basics
import math
print(math.sqrt(16))
2.9 Math module
import math
print(math.sin(math.pi/2))
2.10 Random numbers
import random
print(random.randint(1, 100))
2.11 Representing text
# Representing text with string variables
text = "Python is fun!"
print(text)
2.12 Additional practice: Number games
import random
number = random.randint(1, 10)
guess = int(input("Guess the number between 1 and 10: "))
if guess == number:
print("Correct!")
else:
print("Wrong! The number was:", number)
3.1 String basics
# String operations
string = "Hello, World!"
print(string[0]) # Accessing the first character
print(string[7:12]) # Slicing the string
3.2 String formatting
# String formatting using f-string
name = "Alice"
age = 25
print(f"Name: {name}, Age: {age}")
3.3 List basics
# Lists in Python
fruits = ["apple", "banana", "cherry"]
print(fruits[0])
3.4 Tuple basics
# Tuples are immutable
coordinates = (10, 20)
print(coordinates[0])
3.5 Set basics
# Sets are unordered collections with no duplicates
fruits = {"apple", "banana", "cherry"}
print(fruits)
3.6 Dictionary basics
# Dictionaries store key-value pairs
person = {"name": "Alice", "age": 25}
print(person["name"])
3.7 Additional practice: Grade calculation
# Calculate grade based on score
score = int(input("Enter your score: "))
if score >= 90:
print("Grade A")
elif score >= 80:
print("Grade B")
else:
print("Grade C")
3.8 Type conversions
# Converting between types
num_str = "10"
num = int(num_str)
print(num + 5)
3.9 Binary numbers
# Binary representation
bin_num = bin(10) # Convert decimal to binary
print(bin_num)
3.11 Additional practice: Health data
# Example of storing health data
age = int(input("Enter your age: "))
height = float(input("Enter your height in meters: "))
weight = float(input("Enter your weight in kg: "))
bmi = weight / (height ** 2)
print(f"Your BMI is: {bmi}")
4.2 Detecting equal values with branches
# Detecting if two values are equal
a = 10
b = 10
if a == b:
print("The values are equal")
else:
print("The values are not equal")
4.3 Detecting ranges with branches (general)
# Check if a number falls within a range
num = 15
if 10 <= num <= 20:
print("The number is between 10 and 20")
else:
print("The number is outside the range")
4.4 Detecting ranges with branches
# Check if a number is within a specific range
age = 25
if age >= 18 and age <= 30:
print("Age is between 18 and 30")
else:
print("Age is outside the range")
4.5 Detecting ranges using logical operators
# Using logical operators to check range
temperature = 25
if 20 <= temperature <= 30:
print("The temperature is comfortable")
elif temperature < 20:
print("It's too cold")
else:
print("It's too hot")
4.6 Detecting ranges with gaps
# Detecting if a number is outside two ranges
score = 85
if score < 50 or score > 80:
print("Score is either too low or too high")
else:
print("Score is within the acceptable range")
4.7 Detecting multiple features with branches
# Check multiple features (age and height)
age = 20
height = 170
if age > 18 and height > 150:
print("Eligible for the ride")
else:
print("Not eligible for the ride")
4.8 Comparing data types and common errors
# Comparing different data types
a = 10 # integer
b = "10" # string
# Common error: comparing different types directly without conversion
if a == b:
print("Equal")
else:
print("Not equal")
# Correct approach (convert string to integer)
if a == int(b):
print("Equal after conversion")
4.9 Membership and identity operators
# Membership operator
fruits = ["apple", "banana", "cherry"]
if "banana" in fruits:
print("Banana is in the list")
# Identity operator
x = [1, 2, 3]
y = x # y references the same list object as x
if x is y:
print("x and y are the same object")
4.10 Order of evaluation
# Order of evaluation in logical operators
x = 10
y=5
# AND has higher precedence than OR
if x > 5 and y < 10 or x < 5:
print("Condition is True")
else:
print("Condition is False")
4.11 Code blocks and indentation
# Proper indentation defines blocks of code
age = 20
if age >= 18:
print("Adult")
print("Eligible to vote")
else:
print("Not an adult")
4.12 Conditional expressions
# Using a conditional expression (ternary operator)
age = 17
status = "Adult" if age >= 18 else "Minor"
print(status)
4.13 Additional practice: Tweet decoder
# Decode a short tweet to see if it's a positive or negative message
tweet = "I love Python programming!"
status = "Positive" if "love" in tweet else "Negative"
print(status)
5.1 Loops (general)
# Loop through a list using a for loop
colors = ["red", "green", "blue"]
for color in colors:
print(color)
5.2 While loops
# Using a while loop to print numbers
num = 1
while num <= 5:
print(num)
num += 1
5.3 More while examples
# Using while loop for a countdown
count = 10
while count > 0:
print(count)
count -= 1
print("Blast off!")
5.4 Counting
# Counting occurrences of a specific character in a string
word = "hello"
count = 0
for char in word:
if char == 'l':
count += 1
print("The letter 'l' appears", count, "times")
5.5 For loops
# Loop over a range of numbers
for i in range(1, 6):
print(i)
5.6 Counting using the range() function
# Counting using range function
for i in range(0, 10, 2): # Step size of 2
print(i)
5.7 While vs. for loops
# Using a while loop
i=0
while i < 5:
print(i)
i += 1
# Using a for loop
for i in range(5):
print(i)
5.8 Nested loops
# Nested loop example: printing a 2D grid
for i in range(3):
for j in range(3):
print(f"({i},{j})", end=" ")
print()
5.9 Developing programs incrementally
# Start with a simple version and build it incrementally
# Simple program to sum numbers
total = 0
for i in range(1, 6):
total += i
print("Total sum:", total)
5.10 Break and continue
# Break stops the loop, continue skips to the next iteration
for i in range(1, 6):
if i == 3:
continue # Skip number 3
if i == 5:
break # Stop the loop at number 5
print(i)
5.11 Loop else
# The else block runs after the loop finishes, unless broken out
for i in range(5):
print(i)
else:
print("Loop completed successfully")
5.12 Getting both index and value when looping: enumerate()
# Using enumerate to get both index and value
fruits = ["apple", "banana", "cherry"]
for index, fruit in enumerate(fruits):
print(f"Index: {index}, Fruit: {fruit}")
5.13 Additional practice: Dice statistics
import random
# Simulate rolling a die 100 times
rolls = [random.randint(1, 6) for _ in range(100)]
for i in range(1, 7):
print(f"Side {i}: {rolls.count(i)} times")
6.1 User-defined function basics
# Basic user-defined function
def greet(name):
print(f"Hello, {name}!")
greet("Alice")
6.2 Print functions
# Function to print a custom message
def print_message(message):
print(message)
print_message("This is a custom message!")
6.3 Dynamic typing
# Dynamic typing in Python
x = 10 # Integer
print(x)
x = "Hello" # String
print(x)
6.4 Reasons for defining functions
# Functions improve code reusability and readability
def add(a, b):
return a + b
result = add(5, 7)
print(result)
6.5 Writing mathematical functions
# Mathematical function to calculate the square of a number
def square(x):
return x * x
print(square(4))
6.6 Function stubs
# A function stub with no implementation yet
def calculate_area(radius):
pass # Function not yet implemented
6.7 Functions with branches/loops
# Function with a loop
def count_even_numbers(numbers):
count = 0
for num in numbers:
if num % 2 == 0:
count += 1
return count
print(count_even_numbers([1, 2, 3, 4, 5, 6]))
6.8 Functions are objects
# Functions can be assigned to variables
def greet():
print("Hello!")
greeting_function = greet
greeting_function()
6.9 Functions: Common errors
# Common error: calling a function with incorrect arguments
def add(a, b):
return a + b
# Calling with one argument
# add(5) # This will throw a TypeError: missing 1 required positional argument
6.10 Scope of variables and functions
# Local and global scope
x = 10 # Global variable
def example():
x = 5 # Local variable
print("Local x:", x)
example()
print("Global x:", x)
6.11 Namespaces and scope resolution
# Demonstrating namespaces
x = "Global x"
def example():
x = "Local x"
print(x)
example()
print(x)
6.12 Function arguments
# Function with positional arguments
def greet(name, age):
print(f"Hello {name}, you are {age} years old.")
greet("Alice", 25)
6.13 Keyword arguments and default parameter values
# Function with default parameter values
def greet(name="Guest"):
print(f"Hello, {name}!")
greet()
greet("Alice")
6.14 Arbitrary argument lists
# Using *args to accept a variable number of arguments
def sum_numbers(*args):
return sum(args)
print(sum_numbers(1, 2, 3, 4))
6.15 Multiple function outputs
# Function returning multiple values
def get_min_max(numbers):
return min(numbers), max(numbers)
min_num, max_num = get_min_max([1, 2, 3, 4, 5])
print(min_num, max_num)
6.16 Help! Using docstrings to document functions
# Using docstrings for documentation
def greet(name):
"""
This function greets the person passed as a parameter.
Parameters:
name (str): The name of the person to greet.
"""
print(f"Hello, {name}!")
print(greet.__doc__)
7.1 String slicing
# Slicing strings
word = "Python"
print(word[0:3]) # Output: 'Pyt'
7.2 Advanced string formatting
# Advanced formatting with f-strings
name = "Alice"
age = 25
print(f"Name: {name}, Age: {age}")
7.3 String methods
# String methods
text = " hello world "
print(text.strip()) # Removes whitespace
print(text.lower()) # Converts to lowercase
7.4 Splitting and joining strings
# Splitting and joining strings
text = "apple,banana,cherry"
fruits = text.split(",") # Split into a list
print(fruits)
joined_text = " ".join(fruits) # Join list with space separator
print(joined_text)
8.1 Lists
# Creating and using a list
fruits = ["apple", "banana", "cherry"]
print(fruits) # Output: ['apple', 'banana', 'cherry']
8.2 List methods
# List methods
fruits = ["apple", "banana", "cherry"]
fruits.append("orange") # Add an item at the end
print(fruits) # Output: ['apple', 'banana', 'cherry', 'orange']
fruits.remove("banana") # Remove an item by value
print(fruits) # Output: ['apple', 'cherry', 'orange']
fruits.sort() # Sort the list
print(fruits) # Output: ['apple', 'cherry', 'orange']
fruits.reverse() # Reverse the list
print(fruits) # Output: ['orange', 'cherry', 'apple']
8.3 Iterating over a list
# Iterating over a list using a for loop
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
8.4 List games
# Create a simple game that picks a random number from a list
import random
numbers = [1, 2, 3, 4, 5]
picked_number = random.choice(numbers)
print(f"The picked number is {picked_number}")
8.5 List nesting
# Nested lists
matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
# Accessing elements in a nested list
print(matrix[0][0]) # Output: 1
print(matrix[2][1]) # Output: 8
8.6 List slicing
# Slicing lists
numbers = [1, 2, 3, 4, 5, 6]
print(numbers[2:5]) # Output: [3, 4, 5] (index 2 to 4)
print(numbers[:3]) # Output: [1, 2, 3] (start to index 2)
print(numbers[3:]) # Output: [4, 5, 6] (index 3 to end)
8.7 Loops modifying lists
# Modifying a list within a loop
numbers = [1, 2, 3, 4, 5]
for i in range(len(numbers)):
numbers[i] *= 2 # Double each number
print(numbers) # Output: [2, 4, 6, 8, 10]
8.8 List comprehensions
# Using list comprehensions
numbers = [1, 2, 3, 4, 5]
squared_numbers = [x ** 2 for x in numbers]
print(squared_numbers) # Output: [1, 4, 9, 16, 25]
# Filter even numbers using list comprehension
even_numbers = [x for x in numbers if x % 2 == 0]
print(even_numbers) # Output: [2, 4]
8.9 Sorting lists
# Sorting lists
numbers = [5, 2, 9, 1, 5, 6]
numbers.sort() # Sort in ascending order
print(numbers) # Output: [1, 2, 5, 5, 6, 9]
# Sorting in descending order
numbers.sort(reverse=True)
print(numbers) # Output: [9, 6, 5, 5, 2, 1]
8.10 Command-line arguments
import sys
# Print command-line arguments
print("Script name:", sys.argv[0])
print("Arguments:", sys.argv[1:])
8.11 Additional practice: Engineering examples
# Simple engineering example: Calculate the area of a circle
import math
def calculate_area(radius):
return math.pi * (radius ** 2)
radius = 5
area = calculate_area(radius)
print(f"The area of a circle with radius {radius} is {area:.2f}")
8.12 Dictionaries
# Creating a dictionary
person = {"name": "John", "age": 30, "city": "New York"}
print(person) # Output: {'name': 'John', 'age': 30, 'city': 'New York'}
8.13 Dictionary methods
# Dictionary methods
person = {"name": "John", "age": 30, "city": "New York"}
# Add a new key-value pair
person["job"] = "Engineer"
print(person) # Output: {'name': 'John', 'age': 30, 'city': 'New York', 'job': 'Engineer'}
# Get value by key
print(person.get("age")) # Output: 30
# Remove a key-value pair
person.pop("city")
print(person) # Output: {'name': 'John', 'age': 30, 'job': 'Engineer'}
8.14 Iterating over a dictionary
# Iterating over a dictionary
person = {"name": "John", "age": 30, "city": "New York"}
for key, value in person.items():
print(f"{key}: {value}")
8.15 Dictionary nesting
# Nested dictionaries
person = {
"name": "John",
"address": {
"street": "123 Main St",
"city": "New York"
}
}
print(person["address"]["city"]) # Output: New York
9.1 Classes: Introduction
# Creating a simple class
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
# Creating an object
person1 = Person("Alice", 25)
print(person1.name) # Output: Alice
print(person1.age) # Output: 25
9.2 Classes: Grouping data
# Grouping related data using classes
class Car:
def __init__(self, make, model, year):
self.make = make
self.model = model
self.year = year
# Creating objects
car1 = Car("Toyota", "Camry", 2020)
car2 = Car("Honda", "Civic", 2022)
print(f"{car1.make} {car1.model} ({car1.year})")
9.3 Instance methods
# Instance method in a class
class Dog:
def __init__(self, name, breed):
self.name = name
self.breed = breed
def bark(self):
print(f"{self.name} says woof!")
dog1 = Dog("Buddy", "Golden Retriever")
dog1.bark() # Output: Buddy says woof!
9.4 Class and instance object types
# Checking the type of class and instance objects
class Animal:
pass
class Dog(Animal):
pass
dog = Dog()
print(isinstance(dog, Dog)) # Output: True
print(isinstance(dog, Animal)) # Output: True
print(isinstance(dog, object)) # Output: True
9.5 Class example: Seat reservation system
# Seat reservation system using classes
class Seat:
def __init__(self, seat_number):
self.seat_number = seat_number
self.is_reserved = False
def reserve(self):
if not self.is_reserved:
self.is_reserved = True
print(f"Seat {self.seat_number} reserved.")
else:
print(f"Seat {self.seat_number} is already reserved.")
seat1 = Seat(1)
seat1.reserve() # Output: Seat 1 reserved.
seat1.reserve() # Output: Seat 1 is already reserved.
9.6 Class constructors
# Using constructors to initialize class attributes
class Book:
def __init__(self, title, author):
self.title = title
self.author = author
book1 = Book("1984", "George Orwell")
print(book1.title) # Output: 1984
print(book1.author) # Output: George Orwell
9.7 Class interfaces
# Simulating an interface in Python using abstract base class
from abc import ABC, abstractmethod
class Shape(ABC):
@abstractmethod
def area(self):
pass
class Circle(Shape):
def __init__(self, radius):
self.radius = radius
def area(self):
return 3.14 * self.radius ** 2
circle = Circle(5)
print(circle.area()) # Output: 78.5
9.8 Class customization
# Customizing a class with special methods
class Rectangle:
def __init__(self, width, height):
self.width = width
self.height = height
def __str__(self):
return f"Rectangle({self.width}, {self.height})"
def __add__(self, other):
return Rectangle(self.width + other.width, self.height + other.height)
rect1 = Rectangle(2, 4)
rect2 = Rectangle(3, 5)
rect3 = rect1 + rect2 # Adding two rectangles
print(rect3) # Output: Rectangle(5, 9)
9.9 More operator overloading: Classes as numeric types
# Overloading arithmetic operators in a class
class Vector:
def __init__(self, x, y):
self.x = x
self.y = y
def __add__(self, other):
return Vector(self.x + other.x, self.y + other.y)
def __repr__(self):
return f"Vector({self.x}, {self.y})"
v1 = Vector(1, 2)
v2 = Vector(3, 4)
v3 = v1 + v2
print(v3) # Output: Vector(4, 6)
9.10 Memory allocation and garbage collection
# Example showing memory management and garbage collection
import gc
class LargeObject:
def __init__(self):
self.data = [i for i in range(1000000)]
obj = LargeObject()
print("Before deletion:", gc.get_count())
del obj
gc.collect() # Force garbage collection
print("After deletion:", gc.get_count())
10.1 Handling exceptions using try and except
# Handling exceptions
try:
num = 10 / 0
except ZeroDivisionError as e:
print(f"Error: {e}") # Output: Error: division by zero
10.2 Multiple exception handlers
# Handling multiple exceptions
try:
num = int(input("Enter a number: "))
result = 10 / num
except ZeroDivisionError:
print("Error: Division by zero.")
except ValueError:
print("Error: Invalid input. Please enter a number.")
except Exception as e:
print(f"An unexpected error occurred: {e}")
10.3 Raising exceptions
# Raising an exception
def check_age(age):
if age < 18:
raise ValueError("Age must be 18 or older.")
else:
print(f"Age is {age}, you are allowed.")
try:
check_age(15)
except ValueError as e:
print(e) # Output: Age must be 18 or older.
10.4 Exceptions with functions
# Using exceptions within functions
def divide(a, b):
try:
return a / b
except ZeroDivisionError:
return "Error: Cannot divide by zero."
print(divide(10, 0)) # Output: Error: Cannot divide by zero.
print(divide(10, 2)) # Output: 5.0
10.5 Using finally to clean up
# Using finally for cleanup actions
def file_operations():
try:
file = open('example.txt', 'r')
content = file.read()
print(content)
except FileNotFoundError:
print("File not found.")
finally:
print("Closing the file.")
file.close()
file_operations()
10.6 Custom exception types
# Creating and raising custom exceptions
class InvalidAgeError(Exception):
def __init__(self, message):
self.message = message
super().__init__(self.message)
def check_age(age):
if age < 18:
raise InvalidAgeError("Age must be at least 18.")
try:
check_age(15)
except InvalidAgeError as e:
print(e) # Output: Age must be at least 18.
11.1 Modules
# Creating and using a module (math_operations.py)
# math_operations.py
def add(x, y):
return x + y
def subtract(x, y):
return x - y
# In another script:
import math_operations
result = math_operations.add(5, 3)
print(result) # Output: 8
11.2 Finding modules
# Find installed modules using pip
# Run this in terminal or command prompt:
# pip list
11.3 Importing specific names from a module
# Importing specific functions from a module
from math import pi, sqrt
print(f"Value of Pi: {pi}")
print(f"Square root of 16: {sqrt(16)}")
11.4 Executing modules as scripts
# You can execute a Python file as a script
# In terminal, run:
# python my_script.py
11.5 Reloading modules
import my_module
from importlib import reload
# Modify the content of 'my_module.py' and reload
reload(my_module) # Reloads the module to reflect changes
11.6 Packages
# A package is a collection of Python modules
# Directory structure:
# my_package/
# __init__.py
# module1.py
# module2.py
# Importing from the package:
from my_package import module1
from my_package.module2 import my_function
11.7 Standard library
# Using the standard library (e.g., datetime)
import datetime
today = datetime.date.today()
print(f"Today's date is {today}")
12.1 Reading files
# Reading a file
with open('example.txt', 'r') as file:
content = file.read()
print(content)
12.2 Writing files
# Writing to a file
with open('example.txt', 'w') as file:
file.write("Hello, world!\n")
file.write("This is a test file.")
12.3 Interacting with file systems
import os
# Check if a file exists
if os.path.exists('example.txt'):
print("File exists.")
else:
print("File does not exist.")
# Get current working directory
print(f"Current directory: {os.getcwd()}")
12.4 Binary data
# Writing and reading binary data
data = b"Hello, world!"
with open('binary_file.bin', 'wb') as file:
file.write(data)
with open('binary_file.bin', 'rb') as file:
binary_data = file.read()
print(binary_data) # Output: b'Hello, world!'
12.5 Command-line arguments and files
import sys
# Command-line arguments for reading and writing files
if len(sys.argv) != 3:
print("Usage: python script.py <input_file> <output_file>")
else:
input_file = sys.argv[1]
output_file = sys.argv[2]
with open(input_file, 'r') as infile:
data = infile.read()
with open(output_file, 'w') as outfile:
outfile.write(data)
12.6 The with statement
# Using `with` to handle file opening and closing
with open('example.txt', 'r') as file:
content = file.read()
print(content) # No need to manually close the file
12.7 Comma-separated values (CSV) files
import csv
# Writing to a CSV file
data = [["Name", "Age"], ["Alice", 25], ["Bob", 30]]
with open('people.csv', 'w', newline='') as file:
writer = csv.writer(file)
writer.writerows(data)
# Reading from a CSV file
with open('people.csv', 'r') as file:
reader = csv.reader(file)
for row in reader:
print(row)
Problem 1: Multiple Exception Handlers
Problem: Write a program that prompts the user for a number. If the user enters a non-numeric
value, handle the ValueError. If the user enters zero, handle the ZeroDivisionError. If
any other unexpected error occurs, display a generic error message.
Solution:
try:
num = input("Enter a number: ")
num = int(num)
result = 10 / num
print(f"Result: {result}")
except ZeroDivisionError:
print("Error: You cannot divide by zero.")
except ValueError:
print("Error: Invalid input. Please enter a valid number.")
except Exception as e:
print(f"An unexpected error occurred: {e}")
Explanation:
● If the user enters "abc", a ValueError is raised.
● If the user enters "0", a ZeroDivisionError is raised.
● Any other error will be handled by the generic Exception.
Problem 2: File Operations with finally
Problem: Write a program that attempts to open a file, read its contents, and then ensure that
the file is properly closed using the finally block.
Solution:
def read_file(file_name):
try:
file = open(file_name, 'r')
content = file.read()
print("File contents:")
print(content)
except FileNotFoundError:
print(f"Error: The file {file_name} was not found.")
finally:
try:
file.close()
print("File closed.")
except NameError:
print("No file to close.")
read_file('example.txt')
Explanation:
● The program attempts to open the file and read its contents.
● If the file is not found, a FileNotFoundError is raised.
● Regardless of whether the file is opened successfully, the finally block ensures that
the file is closed. If no file was opened, a NameError is handled to avoid errors when
trying to close a non-existent file.
Problem 3: Sorting and Handling Input for List Operations
Problem: Write a program that takes a list of numbers from the user, sorts the list in ascending
order, and then displays the sorted list. The program should handle invalid input gracefully and
prompt the user again if an invalid value is entered.
Solution:
def sort_numbers():
numbers = []
while True:
try:
user_input = input("Enter a number (or type 'done' to finish): ")
if user_input.lower() == 'done':
break
number = int(user_input)
numbers.append(number)
except ValueError:
print("Invalid input. Please enter a valid number.")
numbers.sort()
print("Sorted numbers:", numbers)
sort_numbers()
Explanation:
● The program repeatedly prompts the user to enter a number.
● If the user enters a non-numeric value, a ValueError is raised, and the user is
prompted to enter a valid number.
● Once the user types "done", the list is sorted and displayed.
Problem 4: Custom Exception Handling
Problem: Write a program that defines a custom exception InvalidAgeError to check if a
person's age is below 18. If the age is below 18, the program should raise this exception and
display a relevant message.
Solution:
class InvalidAgeError(Exception):
def __init__(self, message):
self.message = message
super().__init__(self.message)
def check_age(age):
if age < 18:
raise InvalidAgeError("Age must be at least 18 to proceed.")
else:
print(f"Age {age} is valid!")
try:
check_age(16)
except InvalidAgeError as e:
print(f"Error: {e}")
Explanation:
● The custom exception InvalidAgeError is defined to take a message.
● If the age provided is less than 18, this exception is raised and caught in the try block,
displaying the custom message.
Problem 5: Reading and Writing CSV Files
Problem: Write a program that reads data from a CSV file and writes it to another CSV file.
Handle errors such as the file not existing or permission issues.
Solution:
import csv
def read_and_write_csv(input_file, output_file):
try:
with open(input_file, 'r') as infile:
reader = csv.reader(infile)
data = list(reader)
with open(output_file, 'w', newline='') as outfile:
writer = csv.writer(outfile)
writer.writerows(data)
print("Data successfully copied to", output_file)
except FileNotFoundError:
print(f"Error: The file {input_file} does not exist.")
except PermissionError:
print(f"Error: You do not have permission to access {input_file}.")
except Exception as e:
print(f"An unexpected error occurred: {e}")
read_and_write_csv('input.csv', 'output.csv')
Explanation:
● The program reads data from input.csv and writes it to output.csv.
● It handles FileNotFoundError and PermissionError to deal with file access
issues.
● A generic Exception is used to catch any other unexpected errors.
GUI programming basics with Tkinter:
1. Setting Up a Basic Window
The most fundamental part of a GUI application is the main window. In Tkinter, the Tk class
creates this window.
import tkinter as tk
# Create the main window
window = tk.Tk()
# Set the window title
window.title("My First GUI")
# Set the window size
window.geometry("400x300")
# Start the Tkinter event loop
window.mainloop()
2. Adding Widgets
Widgets are the building blocks of a GUI. Common widgets include labels, buttons, text boxes,
and more.
Example: Label and Button
import tkinter as tk
# Create the main window
window = tk.Tk()
window.title("Widgets Example")
# Add a label
label = tk.Label(window, text="Hello, Tkinter!")
label.pack() # Automatically position the widget
# Add a button
def on_button_click():
label.config(text="Button Clicked!")
button = tk.Button(window, text="Click Me", command=on_button_click)
button.pack()
window.mainloop()
3. Layout Managers
Tkinter provides three layout managers for arranging widgets:
● pack: Simplest method, arranges widgets vertically or horizontally.
● grid: Organizes widgets in a grid of rows and columns.
● place: Allows precise placement by specifying x and y coordinates.
Example: Using grid
import tkinter as tk
window = tk.Tk()
window.title("Grid Layout Example")
# Add labels and entry fields
tk.Label(window, text="First Name:").grid(row=0, column=0)
tk.Label(window, text="Last Name:").grid(row=1, column=0)
entry_first_name = tk.Entry(window)
entry_last_name = tk.Entry(window)
entry_first_name.grid(row=0, column=1)
entry_last_name.grid(row=1, column=1)
window.mainloop()
4. Event Handling
Tkinter allows you to handle user actions like button clicks, key presses, or mouse movements.
Example: Handling Button Clicks
import tkinter as tk
def say_hello():
print("Hello, World!")
window = tk.Tk()
window.title("Event Handling")
button = tk.Button(window, text="Click Me", command=say_hello)
button.pack()
window.mainloop()
5. More Widgets
Here are some other widgets you can use:
● Entry (Text Input):
entry = tk.Entry(window)
entry.pack()
● Checkbutton (Checkbox):
var = tk.BooleanVar()
check = tk.Checkbutton(window, text="I agree", variable=var)
check.pack()
● Radiobuttons:
var = tk.StringVar(value="Option 1")
radio1 = tk.Radiobutton(window, text="Option 1", value="Option 1", variable=var)
radio2 = tk.Radiobutton(window, text="Option 2", value="Option 2", variable=var)
radio1.pack()
radio2.pack()
● Combobox (Dropdown menu):
from tkinter import ttk
combo = ttk.Combobox(window, values=["Option 1", "Option 2", "Option 3"])
combo.pack()
6. Adding Menus
Menus can be added to the GUI using Menu.
Example:
import tkinter as tk
def about():
print("This is a basic GUI app.")
window = tk.Tk()
menu_bar = tk.Menu(window)
# Add "File" menu
file_menu = tk.Menu(menu_bar, tearoff=0)
file_menu.add_command(label="Exit", command=window.quit)
menu_bar.add_cascade(label="File", menu=file_menu)
# Add "Help" menu
help_menu = tk.Menu(menu_bar, tearoff=0)
help_menu.add_command(label="About", command=about)
menu_bar.add_cascade(label="Help", menu=help_menu)
window.config(menu=menu_bar)
window.mainloop()
7. Adding Canvas for Drawing
The Canvas widget allows drawing shapes, lines, or custom graphics.
Example:
import tkinter as tk
window = tk.Tk()
window.title("Canvas Example")
canvas = tk.Canvas(window, width=400, height=300, bg="white")
canvas.pack()
# Draw shapes
canvas.create_rectangle(50, 50, 150, 100, fill="blue")
canvas.create_oval(200, 50, 300, 150, fill="red")
canvas.create_line(0, 0, 400, 300, fill="green")
window.mainloop()
8. Combining Everything: A Basic Calculator
Here’s a more comprehensive example:
import tkinter as tk
def calculate():
try:
result = eval(entry.get())
label_result.config(text=f"Result: {result}")
except Exception as e:
label_result.config(text="Error")
window = tk.Tk()
window.title("Basic Calculator")
entry = tk.Entry(window, width=20)
entry.pack()
button = tk.Button(window, text="Calculate", command=calculate)
button.pack()
label_result = tk.Label(window, text="Result: ")
label_result.pack()
window.mainloop()