Python Assignment for Mid
Python Assignment for Mid
# Method example
class Rectangle:
def __init__(self, length, width):
self.length = length
self.width = width
def get_point():
Point = namedtuple('Point', ['x', 'y'])
return Point(10, 20)
3. Formal vs Actual Arguments in Function Calls
Formal Arguments (Parameters):
Defined in the function definition
Placeholders for values that will be passed when the function is called
Specify the type and number of inputs a function expects
Types include:
o Positional arguments
o Keyword arguments
o Default arguments
o Variable-length arguments (*args)
o Keyword variable-length arguments (**kwargs)
Actual Arguments (Actual Parameters):
Real values passed to a function when it is called
Must match the formal arguments in type, order, and number
Can be passed in multiple ways
Example:
def greet(name, message="Hello"): # name and message are formal arguments
print(f"{message}, {name}!")
try:
validate_age(-5)
except CustomValidationError as e:
print(e)
6. Types of Exceptions in Python
Built-in Exception Categories:
1. Syntax Errors
o Occur during parsing of code
o Prevent code execution
o Example: Incorrect indentation, missing colons
2. Logical Errors
o Errors in program logic
o Code runs but produces incorrect results
3. Runtime Exceptions
o TypeError: Incorrect type operation
o ValueError: Inappropriate value
o ZeroDivisionError: Division by zero
o IndexError: Invalid list index
o KeyError: Non-existent dictionary key
o FileNotFoundError: Missing file
o PermissionError: Insufficient permissions
7. Generators in Python
Generators are special functions that generate a sequence of values over time, rather than computing
them all at once.
Key Characteristics:
Use yield keyword instead of return
Generate values on-the-fly
Memory efficient
Can be iterated
Pause and resume execution
Example:
def fibonacci_generator(n):
a, b = 0, 1
count = 0
while count < n:
yield a
a, b = b, a + b
count += 1
@timer_decorator
def slow_function():
import time
time.sleep(2)
print("Function completed")
9. Recursive Functions in Python
Recursive Function:
A function that calls itself
Solves problems by breaking them into smaller, similar sub-problems
Requires a base case to prevent infinite recursion
Example: Factorial Calculation
def factorial(n):
# Base case
if n == 0 or n == 1:
return 1
# Recursive case
else:
return n * factorial(n - 1)
10. Local vs Global Variables
Local Variables:
Defined inside a function
Accessible only within that function
Created when function starts, destroyed when function ends
Global Variables:
Defined outside any function
Accessible throughout the entire program
global keyword used to modify global variables inside functions
Example:
total = 100 # Global variable
def modify_total():
global total # Indicates we want to modify global variable
total += 50
modify_total()
print(total) # Now 150
11. Defining and Calling Functions in Python
Function Definition:
def function_name(parameters):
"""Optional docstring explaining function"""
# Function body
return value # Optional return statement
Function Calling:
def greet(name):
return f"Hello, {name}!"
Features:
- Type conversion
- Range validation
- Error handling
"""
while True:
try:
# Prompt with clear instructions
age_input = input("Please enter your age (0-120): ")
except ValueError:
# Handles non-numeric inputs
print("Invalid input. Please enter a numeric age.")
# Call demonstration
advanced_loop_techniques()
7. Structured Types: Tuples and Lists - Comprehensive Analysis
Structured Types Theory
Purpose of Structured Types:
Organize and group related data
Provide efficient data storage
Enable complex data manipulations
Support various programming paradigms
Tuples: Immutable Sequences
Theoretical Characteristics:
Fixed, unchangeable after creation
Lightweight data structures
Used for heterogeneous data
Support indexing and slicing
Slightly more memory efficient
Can be used as dictionary keys
Ideal Use Cases:
Representing fixed collections
Returning multiple values from functions
Protecting data from modification
Lists: Mutable Sequences
Theoretical Characteristics:
Dynamic, modifiable collections
Support various mutation operations
Heterogeneous data storage
Flexible sizing
Rich built-in methods
Ideal Use Cases:
Storing collections that change
Implementing stacks, queues
Dynamic data management
Comprehensive Example:
def structured_types_demo():
# Tuple demonstration
coordinates = (10, 20) # Immutable
# List demonstration
numbers = [1, 2, 3] # Mutable
numbers.append(4) # Allowed
# Advanced unpacking
x, y = coordinates
# List comprehension
squared_numbers = [num**2 for num in numbers]
print(f"Coordinates: {coordinates}")
print(f"Squared Numbers: {squared_numbers}")
# Execute demonstration
structured_types_demo()
# Immutable string
immutable_string = "Hello"
# immutable_string[0] = 'h' # Would raise TypeError
new_string = immutable_string.lower() # Creates new string
# Execute demonstration
mutability_demonstration()
# Character-level conversion
text = "Python"
char_list = list(text)
print("Character List:", char_list)
# Execute demonstration
string_to_list_conversion()
Performance and Memory Considerations:
split() creates new list object
Large strings require careful memory management
Consider generator-based approaches for massive texts
Use list comprehensions for efficient transformations
10. Dictionaries in Python - Comprehensive Analysis
Dictionary Theoretical Framework
Core Dictionary Concepts:
Key-value pair storage mechanism
Unordered collection (prior to Python 3.7)
Highly optimized hash table implementation
Provide O(1) average-case lookup
Fundamental data structure for mapping relationships
Dictionary Characteristics:
1. Key Requirements
o Must be immutable
o Unique within dictionary
o Typically strings, numbers, tuples
2. Value Properties
o Can be any Python object
o Mutable or immutable
o Support complex nested structures
Memory and Performance:
Implemented as hash tables
Extremely fast key access
Dynamic resizing capabilities
Minimal collision handling overhead
Advanced Dictionary Operations:
def dictionary_comprehensive_demo():
# Dictionary Creation Techniques
# Literal Construction
student = {
"name": "Alice Johnson",
"age": 20,
"courses": ["Math", "Computer Science"],
"grades": {"Math": 95, "CS": 92}
}
# Dictionary Comprehension
squared_numbers = {x: x**2 for x in range(6)}
print("Squared Numbers Dict:", squared_numbers)
# Dictionary Transformation
inverted_grades = {
grade: subject
for subject, grade in student["grades"].items()
}
print("\nInverted Grades:", inverted_grades)
# Memory-Efficient Dictionary
from types import MappingProxyType