Python Advanced Programming
Q1. Write a program to check if number is even or odd.
Problem Explanation
A number is even if divisible by 2 (remainder 0), otherwise odd. This program uses modulo operator for checking.
Step-By-Step Instructions
- Input a number from user
- Use modulo operator (%) to find remainder
- If remainder is 0, number is even
- Otherwise, number is odd
Code
num = int(input("Enter a number: "))
if num % 2 == 0:
print(f"{num} is even")
else:
print(f"{num} is odd")
Output
Key Concept
Modulo operator (%) returns remainder. This is fundamental to divisibility checking. Demonstrates conditional programming.
Q2. Use of math module (sqrt, factorial).
Problem Explanation
Python's math module provides mathematical functions like sqrt() for square root and factorial() for factorial calculation.
Code
import math
num = int(input("Enter a number: "))
# Calculate square root
sqrt_result = math.sqrt(num)
print(f"Square root of {num}: {sqrt_result}")
# Calculate factorial
fact_result = math.factorial(num)
print(f"Factorial of {num}: {fact_result}")
# Other useful functions
print(f"Absolute value: {math.fabs(-10)}")
print(f"Floor: {math.floor(3.9)}")
print(f"Ceil: {math.ceil(3.2)}")
Output
Key Concept
math module provides optimized mathematical functions. import statement loads modules. This demonstrates standard library usage.
Q3. Create and use custom module (calc.py).
Problem Explanation
Custom modules extend Python functionality. Create calc.py with functions, then import and use in main program.
Code
# calc.py - Custom calculator module
def add(a, b):
return a + b
def subtract(a, b):
return a - b
def multiply(a, b):
return a * b
def divide(a, b):
if b == 0:
return "Cannot divide by zero"
return a / b
Main Program
import calc
x = float(input("Enter first number: "))
y = float(input("Enter second number: "))
print(f"Addition: {calc.add(x, y)}")
print(f"Subtraction: {calc.subtract(x, y)}")
print(f"Multiplication: {calc.multiply(x, y)}")
print(f"Division: {calc.divide(x, y)}")
Key Concept
Modules promote code reusability and organization. import loads module functions. This teaches modular programming principles.
Q4. Input/Output operations with proper error handling.
Problem Explanation
Input/Output requires handling user input, validation, and graceful error management. input() reads strings, requiring type conversion.
Code
try:
name = input("Enter your name: ")
age = int(input("Enter your age: "))
if age < 0 or age > 150:
print("Invalid age!")
else:
print(f"Hello {name}, you are {age} years old")
except ValueError:
print("Error: Please enter valid input")
except Exception as e:
print(f"Unexpected error: {e}")
Key Concept
Try-except blocks catch exceptions. ValueError occurs during invalid conversions. This demonstrates robust input handling.
Q5. File operations (read, write, append).
Problem Explanation
Python provides file handling with open() function. Modes: 'r' (read), 'w' (write), 'a' (append). with statement auto-closes files.
Code
# Write to file
with open("data.txt", "w") as f:
f.write("Python File Operations\n")
f.write("Line 2: Data here\n")
# Read from file
with open("data.txt", "r") as f:
content = f.read()
print("File content:")
print(content)
# Append to file
with open("data.txt", "a") as f:
f.write("Line 3: Appended text\n")
# Read line by line
with open("data.txt", "r") as f:
for line in f:
print(line.strip())
Key Concept
'with' statement ensures proper file closure. Different modes handle different operations. This teaches file I/O fundamentals.
Q6. Exception handling (try, except, finally).
Problem Explanation
Exception handling prevents program crashes. try block contains code, except catches errors, finally runs regardless.
Code
try:
num1 = int(input("Enter dividend: "))
num2 = int(input("Enter divisor: "))
result = num1 / num2
print(f"Result: {result}")
except ZeroDivisionError:
print("Error: Cannot divide by zero")
except ValueError:
print("Error: Please enter valid integers")
except Exception as e:
print(f"Unexpected error: {e}")
finally:
print("Program execution completed")
Key Concept
Multiple except blocks handle different error types. finally ensures cleanup operations. This teaches robust error management.
Q7. Demonstrate use of classes and objects.
Problem Explanation
Classes are blueprints for objects. Attributes store data, methods perform operations. __init__ initializes objects.
Code
class Student:
def __init__(self, name, roll, gpa):
self.name = name
self.roll = roll
self.gpa = gpa
def display(self):
print(f"Name: {self.name}")
print(f"Roll: {self.roll}")
print(f"GPA: {self.gpa}")
def is_passed(self):
return self.gpa >= 2.0
# Create objects
s1 = Student("Alice", 101, 3.8)
s2 = Student("Bob", 102, 1.9)
s1.display()
print(f"Result: {'Pass' if s1.is_passed() else 'Fail'}")
s2.display()
print(f"Result: {'Pass' if s2.is_passed() else 'Fail'}")
Key Concept
self refers to current object. Methods manipulate instance data. Objects encapsulate related functionality. This teaches OOP fundamentals.
Q8. Method overriding with inheritance.
Problem Explanation
Method overriding allows subclasses to redefine parent class methods, providing specific implementations.
Code
class Vehicle:
def __init__(self, name):
self.name = name
def start(self):
print(f"{self.name} is starting...")
class Car(Vehicle):
def start(self):
print(f"{self.name} car engine started")
class Bike(Vehicle):
def start(self):
print(f"{self.name} bike kick started")
# Create objects and call overridden method
car = Car("Tesla")
car.start() # Car specific behavior
bike = Bike("Harley")
bike.start() # Bike specific behavior
Key Concept
Subclasses override parent methods for custom behavior. Polymorphism allows different implementations. This teaches method overriding.
Q9. Inheritance demonstration with single and multiple.
Problem Explanation
Inheritance allows classes to inherit from parent classes. Single inheritance (one parent), multiple inheritance (multiple parents).
Code Example
class Teacher:
def teach(self):
print("Teaching...")
class Researcher:
def research(self):
print("Conducting research...")
# Single Inheritance
class Lecturer(Teacher):
pass
# Multiple Inheritance
class Professor(Teacher, Researcher):
pass
lecturer = Lecturer()
lecturer.teach()
professor = Professor()
professor.teach()
professor.research()
Key Concept
Inheritance promotes code reuse. Child classes inherit parent attributes/methods. Multiple inheritance combines multiple parents. This teaches inheritance hierarchies.
Q10. Method overloading (with default arguments).
Problem Explanation
Python doesn't support traditional overloading. Instead, use default arguments or *args to handle variable parameters.
Code
class Calculator:
# Method with default arguments
def add(self, a, b, c=0):
return a + b + c
# Method with *args (variable arguments)
def multiply(self, *args):
result = 1
for num in args:
result *= num
return result
calc = Calculator()
print(calc.add(5, 10)) # 15
print(calc.add(5, 10, 20)) # 35
print(calc.multiply(2, 3)) # 6
print(calc.multiply(2, 3, 4)) # 24
Key Concept
Default arguments provide flexibility. *args accepts variable number of arguments. This simulates method overloading. This teaches parameter handling.