Download Python Exam Paper
Download Exam Paper
Paper - Solution ✅
Question 1(a)
1. Features of Python
Python is a versatile programming language known for its simplicity and readability. Here are some key features that make Python stand out:
-
Easy to Learn and Read
- Simple, clear syntax
- Uses indentation for code blocks
- Reads almost like English
-
Interpreted Language
- No compilation needed
- Code executes line by line
- Easier debugging
-
High-Level Language
- No need to manage memory
- No need to declare variable types
- Automatic garbage collection
-
Platform Independent
- Write once, run anywhere
- Works on Windows, Mac, Linux
- No need to modify code for different platforms
-
Free and Open Source
- Free to download and use
- Large community support
- Many free libraries available
2. Comparison between C, Java, and Python
| Feature | C | Java | Python |
|---|---|---|---|
| Syntax | Verbose, manual memory control | Structured, class-based | Minimalist, indentation-based |
| Learning Curve | Steep (pointers, memory management) | Moderate (OOP concepts, JVM) | Gentle (readable, dynamic typing) |
| Execution | Compiled to machine code | Compiled to bytecode → JVM | Interpreted (with .pyc caching) |
| Memory Management | Manual (malloc/free) | Automatic (Garbage Collector) | Automatic (GC + reference counting) |
| Speed | Fastest (native execution) | Moderate (JIT optimized) | Slower (interpreted, dynamic) |
| Typing System | Static, weak | Static, strong | Dynamic, strong |
| Variable Declaration | Explicit (e.g., int x;) | Explicit (e.g., int x = 5;) | Implicit (e.g., x = 5) |
| Platform Independence | Platform-specific binaries | WORA (Write Once, Run Anywhere) | OS-agnostic (via interpreter) |
| Concurrency | Threads/processes (OS-dependent) | Multithreading (JVM-managed) | Limited by GIL; async/multiprocess |
| Error Handling | Error codes (errno) | Try/catch (exceptions) | Try/except (exceptions) |
| Standard Library | Minimal (focus on core functions) | Extensive (networking, GUI, etc.) | "Batteries included" (broad scope) |
| Use Cases | OS kernels, embedded systems | Enterprise apps, Android | Scripting, AI/ML, web development |
| Ecosystem | Limited package managers | Maven/Gradle (Java-centric tools) | PyPI (300k+ third-party packages) |
Key Takeaways:
-
Performance vs Productivity
- Use C for speed-critical systems (e.g., device drivers).
- Choose Java for cross-platform enterprise applications.
- Opt for Python for rapid prototyping and data-centric tasks.
-
Memory & Safety
- C offers control but risks segmentation faults.
- Java/Python prevent memory leaks via GC but add overhead.
-
Concurrency Models
- Java’s threads suit I/O-bound tasks.
- Python’s
asyncio/multiprocessing bypass GIL limitations.
-
Typing Trade-offs
- Static typing (C/Java) catches errors early.
- Dynamic typing (Python) speeds up development.
-
Community & Tools
- Python leads in AI/ML libraries (TensorFlow, PyTorch).
- Java dominates Android and banking systems.
- C remains foundational for low-level programming.
### 3. Tuple with Example
A tuple is an ordered, immutable sequence of elements in Python. It is similar to a list but cannot be changed once created.
**Key Features:**
- Created using parentheses ()
- Cannot be modified after creation
- Can contain different data types
- Allows duplicate elements
**Example:**
```python
# Creating a tuple
my_tuple = (1, "Hello", 3.14, True)
# Accessing elements
print(my_tuple[0]) # Output: 1
print(my_tuple[1]) # Output: "Hello"
# Trying to modify (will raise error)
# my_tuple[0] = 2 # This will raise TypeError
# Tuple operations
print(len(my_tuple)) # Output: 4
print(my_tuple.count("Hello")) # Output: 1
print(my_tuple.index(3.14)) # Output: 2
Question 1(b)
1. Operators in Python
Operators are special symbols that perform operations on variables and values.
1. Arithmetic Operators:
# Examples of arithmetic operators
a = 10
b = 3
print(a + b) # Addition: 13
print(a - b) # Subtraction: 7
print(a * b) # Multiplication: 30
print(a / b) # Division: 3.333...
print(a % b) # Modulus: 1
print(a ** b) # Exponentiation: 1000
2. Comparison Operators:
# Examples of comparison operators
x = 5
y = 10
print(x == y) # Equal to: False
print(x != y) # Not equal to: True
print(x > y) # Greater than: False
print(x < y) # Less than: True
print(x >= y) # Greater than or equal to: False
print(x <= y) # Less than or equal to: True
2. Data Types in Python
Python has several built-in data types:
-
Numeric Types
- int (integers): 5, -17, 1000
- float (decimal numbers): 3.14, -0.001, 2.0
- complex (complex numbers): 2+3j
-
Sequence Types
- str (string): "Hello", 'Python'
- list: [1, 2, 3, "hello"]
- tuple: (1, 2, 3, "world")
-
Boolean Type
- bool: True, False
-
Mapping Type
- dict (dictionary):
{"name": "John", "age": 30}
- dict (dictionary):
-
Set Types
- set: 3
- frozenset: frozenset(3)
Example:
# Examples of different data types
integer_num = 5
float_num = 3.14
text = "Hello Python"
my_list = [1, 2, 3]
my_dict = {"name": "John", "age": 25}
is_true = True
3. Python Virtual Machine (PVM)
The Python Virtual Machine (PVM) is the runtime engine of Python. Here's how it works:
-
Definition
- It's the component that executes Python programs
- Acts as an abstraction layer between Python code and computer hardware
-
Working Process
- Python source code (.py) is compiled to bytecode (.pyc)
- Bytecode is executed by the PVM
- PVM provides platform independence
-
Key Features
- Handles memory management
- Manages garbage collection
- Provides security features
- Ensures platform independence
-
Benefits
- Makes Python platform-independent
- Handles low-level operations automatically
- Provides memory management
- Simplifies development process
Question 2(a)
1. Difference between break and continue statements
break statement:
- Terminates the entire loop immediately
- Control flows to the statement after the loop
- Used to exit a loop when a certain condition is met
continue statement:
- Skips the rest of the current iteration
- Control flows to the next iteration of the loop
- Used to skip specific iterations based on a condition
Example showing both:
# Break example
for i in range(5):
if i == 3:
break # Loop stops when i is 3
print(i) # Output: 0, 1, 2
# Continue example
for i in range(5):
if i == 3:
continue # Skips printing when i is 3
print(i) # Output: 0, 1, 2, 4
2. Advantages of Array
-
Efficient Memory Usage
- Stores elements in contiguous memory locations
- Fixed size helps in memory management
-
Fast Access
- Direct access to elements using index
- Constant time O(1) for accessing elements
-
Easy Iteration
- Simple to traverse using loops
- Supports various iteration methods
-
Better Performance
- Optimized for numerical operations
- Efficient for mathematical computations
3. Python Lambda with Example
Lambda is a way to create small anonymous functions in Python. It's also known as a lambda function or anonymous function.
Syntax:
lambda arguments: expression
Examples:
# Simple lambda function
square = lambda x: x**2
print(square(5)) # Output: 25
# Lambda with multiple arguments
sum = lambda a, b: a + b
print(sum(3, 4)) # Output: 7
# Lambda with filter()
numbers = [1, 2, 3, 4, 5, 6]
even_numbers = list(filter(lambda x: x % 2 == 0, numbers))
print(even_numbers) # Output: [2, 4, 6]
# Lambda with map()
numbers = [1, 2, 3, 4]
squared = list(map(lambda x: x**2, numbers))
print(squared) # Output: [1, 4, 9, 16]
Question 2(b)
1. Slicing an Array with Example
Array slicing in Python allows you to extract a portion of an array using the syntax array[start:end:step].
import numpy as np
# Create a sample array
arr = np.array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
# Basic slicing
print(arr[2:5]) # Output: [2, 3, 4]
print(arr[:4]) # Output: [0, 1, 2, 3]
print(arr[6:]) # Output: [6, 7, 8, 9]
# Slicing with step
print(arr[1:8:2]) # Output: [1, 3, 5, 7]
# Negative indices
print(arr[-5:-2]) # Output: [5, 6, 7]
# Reverse array
print(arr[::-1]) # Output: [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
2. Function and Pass by Object Reference
Function Definition:
- A function is a reusable block of code that performs a specific task
- It helps in organizing code and promoting reusability
- Functions in Python are defined using the
defkeyword
Pass by Object Reference:
- Python uses pass by object reference for function arguments
- The reference to the object is passed to the function
- Mutable objects can be modified within the function
- Immutable objects cannot be modified within the function
Example:
# Example with mutable object (list)
def modify_list(lst):
lst.append(4) # Modifies the original list
print("Inside function:", lst)
my_list = [1, 2, 3]
modify_list(my_list)
print("Outside function:", my_list)
# Output:
# Inside function: [1, 2, 3, 4]
# Outside function: [1, 2, 3, 4]
# Example with immutable object (integer)
def modify_number(num):
num += 1 # Creates a new object
print("Inside function:", num)
x = 5
modify_number(x)
print("Outside function:", x)
# Output:
# Inside function: 6
# Outside function: 5
3. Loop Control Statements
Python provides several statements to control the flow of loops:
- break statement
- Terminates the loop completely
- Used to exit a loop when a condition is met
for i in range(5):
if i == 3:
break
print(i) # Output: 0, 1, 2
- continue statement
- Skips the rest of the current iteration
- Continues with the next iteration
for i in range(5):
if i == 3:
continue
print(i) # Output: 0, 1, 2, 4
- pass statement
- Does nothing
- Used as a placeholder
for i in range(5):
if i == 3:
pass # Do nothing
print(i) # Output: 0, 1, 2, 3, 4
- else clause in loops
- Executes when loop completes normally
- Skipped if loop is terminated by break
for i in range(3):
print(i)
else:
print("Loop completed")
# Output:
# 0
# 1
# 2
# Loop completed
## Question 3(a)
### 1. \_\_init\_\_() Function
The \_\_init\_\_() function is like a welcome setup for new objects in Python classes. Think of it as the setup instructions that run automatically when you create something new from your class.
**Simple Example:**
```python
class Student:
def __init__(self, name, age):
self.name = name # Save the student's name
self.age = age # Save the student's age
# Creating a new student
student1 = Student("John", 20)
print(student1.name) # Output: John
print(student1.age) # Output: 20
In this example:
- __init__ runs automatically when we create a new student
- It's like filling out a form with the student's details
selfmeans "this particular student"- The values we pass (name, age) are stored for later use
2. Looping Using List Comprehension
List comprehension is a shorter and easier way to create lists in Python. It's like writing a loop in a single line!
Basic Format:
new_list = [expression for item in list]
Simple Examples:
# Example 1: Making a list of squares
numbers = [1, 2, 3, 4, 5]
squares = [num * num for num in numbers]
print(squares) # Output: [1, 4, 9, 16, 25]
# Example 2: Making a list of even numbers
evens = [num for num in range(10) if num % 2 == 0]
print(evens) # Output: [0, 2, 4, 6, 8]
# Example 3: Converting temperatures
celsius = [0, 10, 20, 30]
fahrenheit = [c * 9/5 + 32 for c in celsius]
print(fahrenheit) # Output: [32.0, 50.0, 68.0, 86.0]
3. Polymorphism
Polymorphism means "many forms" - it's when you can use the same function name for different types of objects, and each object responds in its own way.
Simple Example:
# Different animals make different sounds
class Dog:
def speak(self):
return "Woof!"
class Cat:
def speak(self):
return "Meow!"
# Creating animals
dog = Dog()
cat = Cat()
# Same function name, different results
print(dog.speak()) # Output: Woof!
print(cat.speak()) # Output: Meow!
# We can use them in the same way
animals = [dog, cat]
for animal in animals:
print(animal.speak()) # Each animal makes its own sound
Question 3(b)
1. Inheritance with Example
Inheritance is like passing down features from parents to children. In Python, a class can inherit (receive) properties and methods from another class.
Simple Example:
# Parent class
class Animal:
def __init__(self, name):
self.name = name
def speak(self):
return "Some sound"
# Child class inheriting from Animal
class Dog(Animal):
def speak(self):
return "Woof!"
# Another child class
class Cat(Animal):
def speak(self):
return "Meow!"
# Using the classes
dog = Dog("Buddy")
cat = Cat("Whiskers")
print(f"{dog.name} says: {dog.speak()}") # Output: Buddy says: Woof!
print(f"{cat.name} says: {cat.speak()}") # Output: Whiskers says: Meow!
In this example:
Animalis the parent class (base class)DogandCatare child classes (derived classes)- They inherit the
nameproperty fromAnimal - Each child class has its own version of
speak()
2. Files in Python
A file is a place where you can save data on your computer. Python makes it easy to work with files!
1. Creating and Writing to a File:
# Writing to a file
with open("my_file.txt", "w") as file:
file.write("Hello, this is line 1\n")
file.write("This is line 2\n")
# Adding more content (append mode)
with open("my_file.txt", "a") as file:
file.write("This is line 3\n")
2. Reading from a File:
# Reading entire file
with open("my_file.txt", "r") as file:
content = file.read()
print(content)
# Reading line by line
with open("my_file.txt", "r") as file:
for line in file:
print(line.strip()) # strip() removes extra newlines
3. Common File Operations:
# Different ways to read
with open("my_file.txt", "r") as file:
# Read all lines into a list
lines = file.readlines()
print(lines)
# Read first line
first_line = file.readline()
print(first_line)
3. Creating and Accessing Tuple Elements
Tuples are like lists, but you can't change them after creating them (they're immutable).
1. Creating Tuples:
# Different ways to create tuples
empty_tuple = ()
single_item = (1,) # Don't forget the comma!
numbers = (1, 2, 3, 4, 5)
mixed = (1, "hello", 3.14, True)
# Creating tuple without parentheses
also_tuple = 1, 2, 3, 4, 5
2. Accessing Tuple Elements:
fruits = ("apple", "banana", "orange", "grape", "mango")
# Using index (starts from 0)
print(fruits[0]) # Output: apple
print(fruits[1]) # Output: banana
print(fruits[-1]) # Output: mango (last item)
# Slicing tuples
print(fruits[1:3]) # Output: ('banana', 'orange')
print(fruits[:3]) # Output: ('apple', 'banana', 'orange')
print(fruits[2:]) # Output: ('orange', 'grape', 'mango')
# Tuple operations
print(len(fruits)) # Output: 5 (number of items)
print("apple" in fruits) # Output: True (checking if item exists)
3. Tuple Methods:
numbers = (1, 2, 3, 2, 4, 2, 5)
# count() - count occurrences
print(numbers.count(2)) # Output: 3 (2 appears three times)
# index() - find position
print(numbers.index(4)) # Output: 4 (position of 4)
# Converting to and from lists
my_tuple = (1, 2, 3)
my_list = list(my_tuple) # Tuple to list
back_to_tuple = tuple(my_list) # List to tuple
Remember:
- Tuples are immutable (can't be changed after creation)
- Use parentheses () to create tuples
- Tuples are faster than lists
- Use tuples for data that shouldn't change
Question 4(a)
1. How to Insert Data into MySQL
There are two main ways to insert data into MySQL using Python:
1. Using SQL INSERT Statement:
import mysql.connector
# Connect to database
db = mysql.connector.connect(
host="localhost",
user="your_username",
password="your_password",
database="school"
)
cursor = db.cursor()
# Simple INSERT
sql = "INSERT INTO students (name, age) VALUES (%s, %s)"
values = ("John", 20)
cursor.execute(sql, values)
# Insert multiple records
sql = "INSERT INTO students (name, age) VALUES (%s, %s)"
values = [
("Alice", 22),
("Bob", 21),
("Charlie", 23)
]
cursor.executemany(sql, values)
# Save changes
db.commit()
print("Data inserted successfully!")
2. What is MySQL?
MySQL is a popular database system that helps you store and manage data. Think of it like a super-organized digital filing cabinet!
Key Features:
-
Free and Open Source
- Anyone can use it without paying
- Large community support
-
Easy to Use
- Simple commands to work with data
- Works well with many programming languages
-
Reliable and Secure
- Keeps data safe
- Password protection
- Regular updates
-
Widely Used
- Used by many websites
- Popular with Python applications
- Good for both small and large projects
3. How to Update Data in MySQL Table
Updating data means changing existing information in your database. Here's how to do it:
import mysql.connector
# Connect to database
db = mysql.connector.connect(
host="localhost",
user="your_username",
password="your_password",
database="school"
)
cursor = db.cursor()
# Update single record
sql = "UPDATE students SET age = %s WHERE name = %s"
values = (23, "John")
cursor.execute(sql, values)
# Update multiple records
sql = "UPDATE students SET grade = 'A' WHERE marks >= 90"
cursor.execute(sql)
# Save changes
db.commit()
print("Data updated successfully!")
Question 4(b)
1. Exception and Exception Handling
An exception is an error that happens while your program is running. Exception handling is how we deal with these errors gracefully.
Basic Structure:
try:
# Code that might cause an error
result = 10 / 0 # This will cause an error!
except:
# What to do if an error happens
print("Oops! Something went wrong!")
Better Example with Multiple Exceptions:
try:
# Risky code
number = int(input("Enter a number: "))
result = 100 / number
print(f"Result is: {result}")
except ValueError:
# If user enters text instead of number
print("Please enter a valid number!")
except ZeroDivisionError:
# If user enters zero
print("Cannot divide by zero!")
except:
# For any other errors
print("Something else went wrong!")
else:
# If no error occurred
print("Everything worked fine!")
finally:
# This runs no matter what
print("All done!")
2. Command Line Arguments
Command line arguments are values we can pass to our Python program when we start it. They're like giving instructions to your program before it runs.
Using sys.argv:
import sys
# sys.argv[0] is the program name
# sys.argv[1] onwards are the arguments
print("Program name:", sys.argv[0])
print("Arguments:", sys.argv[1:])
Example Program:
import sys
def main():
# Check if arguments were provided
if len(sys.argv) < 2:
print("Please provide your name!")
return
# Get the name from argument
name = sys.argv[1]
print(f"Hello, {name}!")
# If age is provided
if len(sys.argv) > 2:
age = sys.argv[2]
print(f"You are {age} years old!")
# Run program
if __name__ == "__main__":
main()
To run this program:
python program.py John 25
# Output:
# Hello, John!
# You are 25 years old!
3. Types of Exceptions in Python
Python has many built-in exceptions. Here are the most common ones with examples:
- SyntaxError
- When your code is written incorrectly
# Wrong syntax
if True print("Hello") # Missing colon
# Correct syntax
if True: print("Hello")
- TypeError
- When you use wrong type of data
# Error: can't add string and number
result = "hello" + 5
# Correct way
result = "hello" + str(5)
- ValueError
- When you use right type but wrong value
# Error: can't convert "hello" to integer
number = int("hello")
# Correct way
number = int("123")
- ZeroDivisionError
- When you try to divide by zero
# Error: division by zero
result = 10 / 0
# Better way
denominator = 0
if denominator != 0:
result = 10 / denominator
else:
print("Can't divide by zero!")
- FileNotFoundError
- When trying to access a file that doesn't exist
# Error: file doesn't exist
file = open("missing.txt", "r")
# Better way
try:
file = open("missing.txt", "r")
except FileNotFoundError:
print("File not found!")
- IndexError
- When trying to access a list index that doesn't exist
# Error: list index out of range
my_list = [1, 2, 3]
print(my_list[5])
# Better way
my_list = [1, 2, 3]
if len(my_list) > 5:
print(my_list[5])
else:
print("Index doesn't exist!")
Remember:
- Always try to anticipate possible errors
- Use specific exception types when possible
- Include helpful error messages
- Clean up resources in finally blocks when needed