Python Mid Syllabus Solved
Python Mid Syllabus Solved
# User input
name = input("Enter your name: ")
print(f"Hello, {name}!")
Iteration
Iteration allows repeating a block of code multiple times using loops.
# For loop
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
# While loop
count = 0
while count < 5:
print(count)
count += 1
Structured Types
Tuples
Immutable ordered sequences
Defined using parentheses
coordinates = (10, 20)
x, y = coordinates # Unpacking
Ranges
Generates sequences of numbers
# Range examples
range(5) # 0, 1, 2, 3, 4
range(2, 7) # 2, 3, 4, 5, 6
range(1, 10, 2) # 1, 3, 5, 7, 9
Lists
Mutable ordered sequences
Most versatile structured type
# List operations
numbers = [1, 2, 3, 4, 5]
numbers.append(6) # Add element
numbers.remove(3) # Remove element
sorted_numbers = sorted(numbers) # Sort list
# List comprehension
squares = [x**2 for x in range(5)] # [0, 1, 4, 9, 16]
Dictionaries
Key-value pairs
Unordered, mutable
student = {
"name": "Alice",
"age": 22,
"courses": ["Math", "Computer Science"]
}
print(student["name"]) # Access by key
student["grade"] = "A" # Add new key-value pair
Mutability
Mutable: Can be changed after creation (lists, dictionaries)
Immutable: Cannot be changed after creation (tuples, strings, numbers)
# Demonstrating mutability
# Mutable list
numbers = [1, 2, 3]
numbers[1] = 10 # Allowed
# Immutable tuple
coordinates = (1, 2)
# coordinates[1] = 10 # This would raise an error
## 1. Functions
```python
# Basic function definition
def greet(name):
"""
This function greets the person passed in as a parameter
:param name: Name of the person to greet
:return: Greeting message
"""
return f"Hello, {name}!"
# Function calling
print(greet("Alice"))
```
```python
# Functions as first-class objects
def multiply(x, y):
return x * y
# Function as an argument
def apply_operation(func, x, y):
return func(x, y)
2. **Keyword Arguments**
```python
def introduce(name, age):
print(f"Name: {name}, Age: {age}")
3. **Default Arguments**
```python
def power(base, exponent=2):
return base ** exponent
print(power(3)) # 9 (3^2)
print(power(3, 3)) # 27 (3^3)
```
print(sum_all(1, 2, 3, 4, 5)) # 15
print_info(name="Alice", age=30)
```
print(factorial(5)) # 120
```
@timer_decorator
def slow_function():
import time
time.sleep(2)
print("Function completed")
slow_function()
```
### Generators
```python
def fibonacci_generator(n):
a, b = 0, 1
count = 0
while count < n:
yield a
a, b = b, a + b
count += 1
## 2. Exceptions
# User-defined exceptions
class CustomError(Exception):
def __init__(self, message):
self.message = message
super().__init__(self.message)
def check_age(age):
if age < 0:
raise CustomError("Age cannot be negative")
try:
check_age(-5)
except CustomError as e:
print(e)
```
## 3. Modules
### Creating Custom Modules
```python
# math_operations.py
def add(a, b):
return a + b
# In another file
import math_operations
print(math_operations.add(5, 3))
```
## 4. File Handling
# Constructor method
def __init__(self, account_number, balance=0):
# Instance attributes
self.account_number = account_number
self.balance = balance
self.transaction_history = []
# Instance method
def deposit(self, amount):
if amount > 0:
self.balance += amount
self.transaction_history.append(f"Deposit: +${amount}")
return True
return False
### Inheritance
Inheritance allows a class to inherit attributes and methods from another class.
```python
class SavingsAccount(BankAccount):
def __init__(self, account_number, interest_rate=0.05):
# Call parent class constructor
super().__init__(account_number)
self.interest_rate = interest_rate
def apply_interest(self):
interest = self.balance * self.interest_rate
self.deposit(interest)
return interest
# Multilevel Inheritance
class PremiumSavingsAccount(SavingsAccount):
def __init__(self, account_number, interest_rate=0.07, min_balance=1000):
super().__init__(account_number, interest_rate)
self.min_balance = min_balance
def check_min_balance(self):
return self.balance >= self.min_balance
```
```python
class SecureBankAccount:
def __init__(self, account_number):
# Private attributes (convention in Python)
self.__account_number = account_number
self.__balance = 0
self.__pin = None
# Getter method
def get_account_number(self):
return self.__account_number
```python
class Bank:
def __init__(self, name):
self.name = name
self.accounts = {}
if account_type == "basic":
account = BankAccount(account_number, initial_deposit)
elif account_type == "savings":
account = SavingsAccount(account_number)
elif account_type == "premium":
account = PremiumSavingsAccount(account_number)
else:
raise ValueError("Invalid account type")
self.accounts[account_number] = account
return account_number
# Example usage
def banking_simulation():
# Create a bank
my_bank = Bank("Global Banking Corporation")
# Create accounts
savings_account = my_bank.create_account("savings", 1000)
checking_account = my_bank.create_account("basic", 500)
# Retrieve accounts
savings = my_bank.get_account(savings_account)
checking = my_bank.get_account(checking_account)
# Perform operations
savings.deposit(500)
savings.apply_interest()
# Transfer funds
checking.withdraw(200)
savings.deposit(200)
# Static method
@staticmethod
def is_prime(n):
if n < 2:
return False
for i in range(2, int(n**0.5) + 1):
if n % i == 0:
return False
return True
```
### Polymorphism
```python
class Shape:
def area(self):
pass
class Rectangle(Shape):
def __init__(self, width, height):
self.width = width
self.height = height
def area(self):
return self.width * self.height
class Circle(Shape):
def __init__(self, radius):
self.radius = radius
def area(self):
return 3.14 * self.radius ** 2
# Polymorphic behavior
def print_area(shape):
print(f"Area: {shape.area()}")
# Usage
rect = Rectangle(5, 3)
circle = Circle(4)