Python Programming: Functions, Packages, and OOP Concepts
Python Functions
1. Definition: Functions are defined using the def keyword.
2. Parameters: Accept inputs (arguments) to customize behavior.
3. Return Values: Functions can return outputs using the return statement.
4. Call: A function is executed when it’s called.
Python Packages
In Python, a package is a way to organize related modules (Python files) into a directory structure, making it easier to manage and reuse code. It allows for a hierarchical organization of the codebase.
Key Features of a Package
1. Directory Structure: A package is essentially a directory containing an __init__.py file and other Python modules.
2. __init__.py File: This file makes the directory a package. It can be empty or contain initialization code for the package.
3. Subpackages: A package can contain other packages, forming a hierarchy.
Importing Modules in Python
In Python, import is used to include modules or specific components into your code.
Examples:
1. Importing a module:
import math
print(math.sqrt(16)) # Output: 4.0
2. Importing specific items:
from math import sqrt
print(sqrt(25)) # Output: 5.0
3. Using aliases:
import numpy as np
print(np.array([1, 2, 3]))
Custom or third-party modules can also be imported to reuse functionality.
Common Python Questions
1. What is the difference between a list and a tuple?
A list is mutable (can be changed), while a tuple is immutable (cannot be changed).
2. What does the len() function do in Python?
The len() function returns the number of items in an object like a list, string, or tuple.
Example: len("hello") gives 5.
3. What is the purpose of the def keyword?
The def keyword is used to define a function in Python.
Example:
def greet():
return "Hello"
4. What is the difference between is and == in Python?
is checks object identity, while == checks value equality.
5. What does pass do in Python?
The pass statement is a placeholder that does nothing.
Example:
if True:
pass
Examples of Common 5-Mark Questions in Python
1. Explain the concept of Python functions with an example.
A function is a block of reusable code that performs a specific task. It is defined using the def keyword.
Example:
def add_numbers(a, b):
return a + b
print(add_numbers(3, 5)) # Output: 8
2. Differentiate between Python lists and dictionaries.
List: An ordered collection of items, accessed by index.
Example: my_list = [1, 2, 3]
Dictionary: A collection of key-value pairs, accessed by keys.
Example: my_dict = {'name': 'Alice', 'age': 25}
3. Explain the use of loops in Python with examples.
For Loop: Used to iterate over a sequence.
Example:
for i in range(3):
print(i) # Output: 0, 1, 2
While Loop: Repeats as long as a condition is true.
Example:
i = 0
while i < 3:
print(i) # Output: 0, 1, 2
i += 1
4. What are Python modules? How do you import and use them?
A module is a file containing Python code (functions, classes, variables) that can be reused in other programs. Use the import statement to include it.
Example:
import math
print(math.sqrt(16)) # Output: 4.0
5. Explain exception handling in Python with an example.
Exception handling is done using try, except, else, and finally blocks to manage runtime errors.
Example:
try:
num = int(input("Enter a number: "))
print(10 / num)
except ZeroDivisionError:
print("Cannot divide by zero.")
except ValueError:
print("Invalid input.")
Examples of 10-Mark Questions in Python
1. Explain Object-Oriented Programming (OOP) in Python with examples.
OOP is a programming paradigm based on the concept of objects, which contain data (attributes) and methods (functions). Python supports OOP with features like classes and inheritance.
Key Concepts:
- Class: Blueprint for objects.
- Object: Instance of a class.
- Inheritance: Reusing code from a parent class.
- Encapsulation: Restricting access to data.
Example:
class Animal:
def __init__(self, name):
self.name = name
def speak(self):
return "I am an animal"
class Dog(Animal): # Inheritance
def speak(self):
return f"{self.name} says Woof!"
dog = Dog("Buddy")
print(dog.speak()) # Output: Buddy says Woof!
2. Describe Python’s file handling with examples.
Python provides built-in functions to handle files using the open() function with modes like r (read), w (write), a (append), etc.
Example:
# Writing to a file
with open("example.txt", "w") as file:
file.write("Hello, Python!")
# Reading from a file
with open("example.txt", "r") as file:
content = file.read()
print(content) # Output: Hello, Python!
3. Explain Python decorators with examples.
Decorators are functions that modify the behavior of other functions or methods.
Example:
def decorator(func):
def wrapper():
print("Before the function call")
func()
print("After the function call")
return wrapper
@decorator # Applying the decorator
def say_hello():
print("Hello!")
say_hello()
# Output:
# Before the function call
# Hello!
# After the function call
4. Explain Python’s exception handling mechanism with examples.
Python uses try, except, else, and finally to handle exceptions, ensuring that the program doesn’t crash due to runtime errors.
Example:
try:
num = int(input("Enter a number: "))
print(10 / num)
except ZeroDivisionError:
print("Cannot divide by zero.")
except ValueError:
print("Invalid input. Enter a number.")
else:
print("No errors!")
finally:
print("Execution complete.")
5. Describe Python’s data structures (list, tuple, set, dictionary) with examples.
List: Ordered, mutable collection.
my_list = [1, 2, 3]
my_list.append(4)
print(my_list) # Output: [1, 2, 3, 4]
Tuple: Ordered, immutable collection.
my_tuple = (1, 2, 3)
print(my_tuple[1]) # Output: 2
Set: Unordered, mutable, unique elements.
my_set = {1, 2, 2, 3}
print(my_set) # Output: {1, 2, 3}
Dictionary: Unordered collection of key-value pairs.
my_dict = {"name": "Alice", "age": 25}
print(my_dict["name"]) # Output: Alice
