1.
Define Function
A function in Python is defined using the 'def' keyword followed by the function name and
parameters.
Example:
def greet(name):
print("Hello", name)
2. Define Module
A module is a file containing Python code. It allows code reuse and modular programming.
Example (mymodule.py):
def add(a, b):
return a + b
3. Define Package
A package is a collection of Python modules organized in directories containing an __init__.py file.
Structure:
mypackage/
__init__.py
module1.py
4. Parameter Passing to Function
Python supports positional, keyword, default, and variable-length arguments.
Example:
def add(a, b=5):
return a + b
5. Self Parameter
In class methods, 'self' refers to the instance of the class.
Example:
class Student:
def __init__(self, name):
self.name = name
6. File Handling Functions
- read(): Reads entire file
- readline(): Reads one line
- write(): Writes a string
- writelines(): Writes a list of strings
- seek(): Moves pointer
- tell(): Shows pointer position
7. Functions of Directories
- os.mkdir(): Creates directory
- os.rmdir(): Removes directory
- os.listdir(): Lists items
- os.getcwd(): Gets current directory
- os.chdir(): Changes directory
8. Exception Handling Keywords
- try: Test for errors
- except: Handle errors
- finally: Always runs
- raise: Raise exception manually
Example:
try:
x=1/0
except ZeroDivisionError:
print("Error")
finally:
print("Done")
9. Alternate Way to Achieve Method Overloading
Use default or variable-length arguments since Python doesn't support traditional overloading.
Example:
def show(*args):
for i in args:
print(i)
10. Programs
1. Accept string and count upper/lowercase:
s = input("Enter string: ")
upper = sum(1 for c in s if c.isupper())
lower = sum(1 for c in s if c.islower())
print("Upper:", upper, "Lower:", lower)
2. User Defined Module:
# my_module.py
def greet():
print("Hello")
# main.py
import my_module
my_module.greet()
3. Parameterized Constructors:
class Base:
def __init__(self, x):
print("Base:", x)
class Derived(Base):
def __init__(self, x, y):
super().__init__(x)
print("Derived:", y)
4. Read first 11 chars of first line:
with open("sample.txt") as f:
line = f.readline()
print(line[:11])