Python codes .pdf
Python codes .pdf
1 Programming (general)
Explanation: Python is a high-level programming language known for its simplicity and
readability.
Explanation: Python can interact with the user through input and output.
1.4 Errors
Explanation: Errors in programming can occur due to syntax mistakes or logical issues.
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 basic understanding of computer components like the CPU, RAM, and hard
drive is useful for understanding how programs run.
Explanation: Python was created by Guido van Rossum in 1989, and was released in 1991. It
was designed to emphasize code readability.
Explanation: Python uses indentation to define blocks of code instead of braces {}.
if True:
print("This is indented correctly!")
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
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
# 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")
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")
greet("Alice")
result = add(5, 7)
print(result)
print(square(4))
print(count_even_numbers([1, 2, 3, 4, 5, 6]))
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
def example():
x = 5 # Local variable
print("Local x:", x)
example()
print("Global x:", x)
def example():
x = "Local x"
print(x)
example()
print(x)
greet("Alice", 25)
greet()
greet("Alice")
print(sum_numbers(1, 2, 3, 4))
Parameters:
name (str): The name of the person to greet.
"""
print(f"Hello, {name}!")
print(greet.__doc__)
8.1 Lists
# Creating and using a list
fruits = ["apple", "banana", "cherry"]
print(fruits) # Output: ['apple', 'banana', 'cherry']
numbers = [1, 2, 3, 4, 5]
picked_number = random.choice(numbers)
print(f"The picked number is {picked_number}")
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'}
# Creating an object
person1 = Person("Alice", 25)
print(person1.name) # Output: Alice
print(person1.age) # Output: 25
# Creating objects
car1 = Car("Toyota", "Camry", 2020)
car2 = Car("Honda", "Civic", 2022)
def bark(self):
print(f"{self.name} says woof!")
class Dog(Animal):
pass
dog = Dog()
print(isinstance(dog, Dog)) # Output: True
print(isinstance(dog, Animal)) # Output: True
print(isinstance(dog, object)) # Output: True
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
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
def __str__(self):
return f"Rectangle({self.width}, {self.height})"
rect1 = Rectangle(2, 4)
rect2 = Rectangle(3, 5)
rect3 = rect1 + rect2 # Adding two rectangles
print(rect3) # Output: Rectangle(5, 9)
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)
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
try:
check_age(15)
except ValueError as e:
print(e) # Output: Age must be 18 or older.
file_operations()
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
# In another script:
import math_operations
result = math_operations.add(5, 3)
print(result) # Output: 8
11.6 Packages
# A package is a collection of Python modules
# Directory structure:
# my_package/
# __init__.py
# module1.py
# module2.py
today = datetime.date.today()
print(f"Today's date is {today}")
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:
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: 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:
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:
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
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.
The most fundamental part of a GUI application is the main window. In Tkinter, the Tk class
creates this window.
import tkinter as tk
2. Adding Widgets
Widgets are the building blocks of a GUI. Common widgets include labels, buttons, text boxes,
and more.
# Add a button
def on_button_click():
label.config(text="Button Clicked!")
window.mainloop()
3. Layout Managers
window = tk.Tk()
window.title("Grid Layout Example")
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.
def say_hello():
print("Hello, World!")
window = tk.Tk()
window.title("Event Handling")
window.mainloop()
5. More Widgets
entry = tk.Entry(window)
entry.pack()
● Checkbutton (Checkbox):
var = tk.BooleanVar()
check = tk.Checkbutton(window, text="I agree", variable=var)
check.pack()
● Radiobuttons:
6. Adding Menus
Example:
import tkinter as tk
def about():
print("This is a basic GUI app.")
window = tk.Tk()
menu_bar = tk.Menu(window)
window.config(menu=menu_bar)
window.mainloop()
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()
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")
window.mainloop()