Advanced Python - Detailed Notes for Class 10
1. Functions
Functions help us organize code into reusable blocks.
- Defined using `def` keyword.
- Can accept parameters and return values.
Example:
def add(a, b):
return a + b
print(add(3, 4)) # Output: 7
Types of Functions:
- Built-in Functions: print(), len(), type(), etc.
- User-defined Functions
- Recursive Functions (function calling itself)
Return Statement:
- Used to send a result back from the function to the caller.
2. File Handling
Python allows us to work with files using functions like open(), read(), write(), etc.
Modes:
Advanced Python - Detailed Notes for Class 10
- 'r': Read (default)
- 'w': Write
- 'a': Append
- 'b': Binary
- 'x': Create
Example:
with open("data.txt", "r") as file:
content = file.read()
print(content)
File Methods:
- read(), readline(), readlines(), write(), writelines(), close()
3. Object-Oriented Programming (OOP)
OOP is a way to structure code using classes and objects.
Key Concepts:
- Class: A blueprint for creating objects.
- Object: An instance of a class.
- Constructor: __init__() method to initialize objects.
- Inheritance: One class inherits properties of another.
- Encapsulation: Hiding internal details of class.
Advanced Python - Detailed Notes for Class 10
Example:
class Student:
def __init__(self, name):
self.name = name
def display(self):
print("Student Name:", self.name)
s1 = Student("Rahul")
s1.display()
4. Exception Handling
Used to manage errors in a graceful way.
Syntax:
try:
# code that may cause error
except ErrorType:
# code to handle error
Common Exceptions:
- ZeroDivisionError
- ValueError
- FileNotFoundError
Advanced Python - Detailed Notes for Class 10
Example:
try:
num = int(input("Enter a number: "))
print(10 / num)
except ZeroDivisionError:
print("Cannot divide by zero!")
5. Modules and Packages
Modules are files containing Python code. Packages are directories containing modules.
Importing Modules:
- import module_name
- from module_name import function_name
Example:
import math
print(math.pi)
6. List Comprehensions
A concise way to create lists.
Syntax:
Advanced Python - Detailed Notes for Class 10
[expression for item in iterable if condition]
Example:
squares = [x**2 for x in range(10) if x % 2 == 0]
print(squares)
7. Lambda Functions
Small anonymous functions defined using the lambda keyword.
Syntax:
lambda arguments: expression
Example:
add = lambda x, y: x + y
print(add(2, 3)) # Output: 5
8. Iterators and Generators
Iterators:
- Objects with __iter__() and __next__() methods.
- Used to iterate over iterable objects.
Generators:
- Functions using yield instead of return.
Advanced Python - Detailed Notes for Class 10
- Generate values one at a time.
Example:
def gen():
for i in range(3):
yield i
for val in gen():
print(val)