@codewithtanvir_ @OfficialCodewithTanvir
Comprehensive Python Notes for Study, Interviews & Exams
Introduction
Brief History of Python
Created by Guido van Rossum in 1991.
Designed for readability, simplicity, and versatility.
Named after "Monty Python's Flying Circus" (not the snake).
Evolved through versions (Python 2.x and Python 3.x, with 3.x now
standard).
Importance and Usage
Widely used in web development, data science, AI/ML, scripting,
automation, scientific computing, and education.
Known for its simple syntax and extensive libraries.
Used by companies like Google, NASA, Instagram, Dropbox.
Beginner Topics
Basic Syntax and Keywords
Python is case-sensitive.
Uses indentation (4 spaces recommended) instead of braces for
blocks.
Keywords: if, elif, else, for, while, def, class, try, except, etc.
Variables, Constants & Data Types
Variables store data with dynamic typing.
Constants: by convention, uppercase names (e.g., PI = 3.14), but
not enforced.
Data types:
o int (integer numbers)
o float (decimal numbers)
o str (strings)
o bool (True/False)
@Copyright content – https:// [Link]
@codewithtanvir_ @OfficialCodewithTanvir
python
age = 25 # int
price = 19.99 # float
name = "Alice" # string
is_student = True # bool
Input and Output
Input from user: input()
Output to console: print()
python
name = input("Enter your name: ")
print("Hello,", name)
Operators
Arithmetic: +, -, *, /, // (floor division), %, ** (power)
Comparison: ==, !=, <, >, <=, >=
Logical: and, or, not
Assignment: =, +=, -=, etc.
Conditional Statements
Execute code based on conditions.
python
if age >= 18:
print("Adult")
elif age > 12:
print("Teenager")
else:
print("Child")
Loops
for loop to iterate over sequences.
while loop for repeated execution based on a condition.
break to exit loop early.
@Copyright content – https:// [Link]
@codewithtanvir_ @OfficialCodewithTanvir
continue to skip the current iteration.
python
for i in range(5):
if i == 3:
continue
print(i)
count = 0
while count < 5:
print(count)
count += 1
Functions
Defined by def keyword.
Use parameters and optional return values.
python
def greet(name):
return "Hello " + name
print(greet("Bob"))
Lists, Tuples, Sets, Dictionaries
Lists: ordered, mutable
Tuples: ordered, immutable
Sets: unordered, unique elements
Dicts: key-value pairs
python
fruits = ["apple", "banana", "cherry"] # list
coordinates = (10.0, 20.0) # tuple
unique_numbers = {1, 2, 3} # set
student = {"name": "Alice", "age": 23} # dict
@Copyright content – https:// [Link]
@codewithtanvir_ @OfficialCodewithTanvir
String Operations & Formatting
Manipulation: slicing, concatenation, methods (lower(), upper(),
strip(), etc.).
Formatting with f-strings (Python 3.6+):
python
name = "John"
age = 30
print(f"My name is {name} and I am {age} years old.")
Basic Error Handling
try and except to handle exceptions.
python
try:
x = int(input("Enter a number: "))
print(10 / x)
except ZeroDivisionError:
print("Cannot divide by zero.")
except ValueError:
print("Invalid input. Please enter a number.")
Pro Tips for Beginners
Build mini projects (e.g., calculator, guessing game) for hands-on
practice.
Use list comprehensions for more concise loops.
Always comment your code clearly.
Intermediate Topics
Advanced Data Structures
Stacks & Queues using list or [Link].
Linked lists can be simulated via custom classes or lists.
python
from collections import deque
@Copyright content – https:// [Link]
@codewithtanvir_ @OfficialCodewithTanvir
queue = deque()
[Link]('a')
[Link]()
File Handling
Read/write text and CSV files.
python
with open("[Link]", "r") as f:
data = [Link]()
with open("[Link]", "w") as f:
[Link]("Hello, File!")
Functions: Default Arguments, *args, **kwargs
Default values:
python
def greet(name="Guest"):
print(f"Hello, {name}")
Variable number positional arguments:
python
def add(*args):
return sum(args)
Variable keyword arguments:
python
def person_info(**kwargs):
for key, value in [Link]():
print(f"{key}: {value}")
Modules & Packages
Import libraries: import math, from os import path.
Create your own modules by saving .py files and importing them.
Exception Handling Enhancements
@Copyright content – https:// [Link]
@codewithtanvir_ @OfficialCodewithTanvir
finally block for cleanup.
raise to throw exceptions.
Object-Oriented Programming (OOP)
Classes & objects:
python
class Dog:
def __init__(self, name):
[Link] = name
def bark(self):
return "Woof!"
dog = Dog("Rex")
print([Link]())
Inheritance:
python
class Puppy(Dog):
def bark(self):
return "Yip!"
Polymorphism, Encapsulation (private variables using _ or __),
Abstraction via abstract base classes.
Iterators & Generators
Iterator protocol using __iter__, __next__.
Generator functions with yield.
python
def count_up_to(n):
count = 1
while count <= n:
yield count
@Copyright content – https:// [Link]
@codewithtanvir_ @OfficialCodewithTanvir
count += 1
Decorators & Higher-Order Functions
Functions that modify other functions.
python
def decorator(func):
def wrapper():
print("Before call")
func()
print("After call")
return wrapper
@decorator
def say_hello():
print("Hello")
say_hello()
Virtual Environments
Use venv to create isolated Python environments.
Install packages via pip.
Popular Libraries
NumPy: Efficient array computations.
Pandas: Data manipulation and analysis.
Matplotlib: Visualization.
Pro Tips for Intermediate Coding
Follow PEP8 style guide.
Write modular programs.
Contribute small open-source code to strengthen OOP
understanding.
@Copyright content – https:// [Link]
@codewithtanvir_ @OfficialCodewithTanvir
Advanced Topics
Functional Programming
Use map(), filter(), reduce(), lambda.
python
nums = [1, 2, 3, 4]
squared = list(map(lambda x: x**2, nums))
even = list(filter(lambda x: x % 2 == 0, nums))
Context Managers (with statement)
Ensure resources are managed and released properly.
python
with open("[Link]") as f:
data = [Link]()
Custom context managers with __enter__ and __exit__.
Advanced OOP
Abstract classes (abc module).
Multiple inheritance.
Metaclasses for advanced type control.
Concurrency & Parallelism
Multi-threading (threading).
Multi-processing (multiprocessing).
Asyncio for asynchronous programming (async, await).
Memory Management & Garbage Collection
Python uses reference counting and a cyclic GC.
Understand object lifecycle and memory leaks in complex programs.
Design Patterns
Singleton, Factory, Observer, and more adapted to Python context.
Databases with Python
Use sqlite3 for lightweight DB.
Connect to MySQL, MongoDB via connectors.
@Copyright content – https:// [Link]
@codewithtanvir_ @OfficialCodewithTanvir
Web Frameworks
Flask and Django basics for building web apps.
REST API Creation & Consumption
Use frameworks like Flask-RESTful.
Requests library for API calls.
Testing Frameworks
unittest and pytest for unit testing code.
Packaging & Distribution
Create installable packages with setuptools and distribute via PyPI.
Data Science and AI Integration
Use NumPy, Pandas, Matplotlib for data.
Scikit-learn for ML.
TensorFlow / PyTorch for deep learning.
Pro Tips for Advanced Users
Optimize code and learn time complexity.
Write unit tests rigorously.
Read documentation and source code.
Apply design patterns.
Build full-stack projects and real-world applications.
Practical Examples
Beginner Example: Calculator
python
def calculator():
x = float(input("Enter first number: "))
op = input("Enter operator (+, -, *, /): ")
y = float(input("Enter second number: "))
if op == '+':
print(x + y)
@Copyright content – https:// [Link]
@codewithtanvir_ @OfficialCodewithTanvir
elif op == '-':
print(x - y)
elif op == '*':
print(x * y)
elif op == '/':
if y != 0:
print(x / y)
else:
print("Cannot divide by zero")
else:
print("Invalid operator")
calculator()
Intermediate Example: File Reader with Exception Handling
python
def read_file(filename):
try:
with open(filename, 'r') as file:
data = [Link]()
print(data)
except FileNotFoundError:
print("File not found", filename)
read_file('[Link]')
Advanced Example: Basic Flask REST API
python
from flask import Flask, jsonify, request
app = Flask(__name__)
@Copyright content – https:// [Link]
@codewithtanvir_ @OfficialCodewithTanvir
@[Link]('/api/greet', methods=['GET'])
def greet():
name = [Link]('name', 'Guest')
return jsonify(message=f"Hello, {name}!")
if __name__ == '__main__':
[Link](debug=True)
Interview Preparation
Top 20 Frequently Asked Questions (Sample)
1. What are Python’s key features?
2. Explain Python's memory management.
3. Difference between list and tuple.
4. How does Python handle exceptions?
5. What are decorators?
6. Explain *args and **kwargs.
7. How do you manage packages in Python?
8. What is list comprehension?
9. Difference between shallow and deep copy.
10. What are Python generators?
11. Explain GIL (Global Interpreter Lock).
12. How do you handle missing files in file I/O?
13. What are lambda functions?
14. How do you implement OOP in Python?
15. What is a Python module and package?
16. How to connect Python with a database?
17. What is a virtual environment?
18. Explain Python’s multithreading vs multiprocessing.
@Copyright content – https:// [Link]
@codewithtanvir_ @OfficialCodewithTanvir
19. What are Python’s built-in data structures?
20. How can you optimize Python code?
Common Mistakes & Pitfalls
Ignoring indentation rules.
Mutable default arguments in functions.
Forgetting to close files or use context managers.
Misusing is vs ==.
Overlooking exception handling.
Not following PEP8.
Cheat Sheet / Quick Revision
Concept Syntax / Use
Variable
x = 10
Declaration
Function
def func(arg): return arg*2
Definition
If Statement if condition: ... elif ... else ...
Loop (for) for i in range(5): print(i)
Loop (while) while condition: ...
List lst = [1, 2, 3]
Tuple t = (1, 2)
Set s = {1,2,3}
Dict d = {'key': 'value'}
Try-Except try: ... except Error: ...
Class class MyClass: def __init__(): ...
import math or from math
Import Module
import sqrt
List [x for x in range(10) if x % 2 ==
Comprehension 0]
@Copyright content – https:// [Link]
@codewithtanvir_ @OfficialCodewithTanvir
Concept Syntax / Use
Lambda Function lambda x: x**2
Decorator @decorator above a function
Would you like me to create tailored mini-project examples for each level
or a detailed interview question-answer guide?
@Copyright content – https:// [Link]