Python_Notes_Basic_to_Advanced
Python_Notes_Basic_to_Advanced
1. Introduction to Python
4. Operators
5. Strings in Detail
6. Lists
7. Tuples
8. Sets
9. Dictionaries
12. Functions
14. Comprehensions
21. Decorators
What is Python?
Python is a simple, readable, and powerful programming language created by Guido van Rossum and released in 1991. It is called a "high-level" language
because it is written in a way that is close to human language, instead of complicated machine instructions.
Think of Python like giving instructions to a very obedient friend, one step at a time, in plain English-like sentences. That is exactly what a Python program looks
like.
Easy to Read and Write: Python's syntax looks almost like English.
Beginner Friendly: It is one of the best first languages to learn.
Extremely Versatile: Used in web development, data science, artificial intelligence, automation, game development, and more.
Huge Community: Millions of developers, endless tutorials, and free libraries.
Free and Open Source: Anyone can download and use it without paying anything.
Simple Analogy: If programming languages were vehicles, Python would be a bicycle - easy to learn, easy to ride, but can still take you very far.
Features of Python
Interpreted: Code runs line by line, which makes it easier to test and debug.
Dynamically Typed: You don't need to declare the data type of a variable.
Object-Oriented: Supports classes and objects.
Cross-Platform: Works on Windows, macOS, and Linux.
2. Installing Python and Setup
Go to the official website [Link] and download the latest version for your operating system (Windows, Mac, or Linux).
Step 2: Install It
Run the installer. On Windows, make sure to check the box that says "Add Python to PATH" before clicking install. This lets you run Python from anywhere in
the command line.
python --version
You can write Python code in any text editor, but these are popular choices for beginners:
print("Hello, World!")
python [Link]
Congratulations - you just wrote and ran your first Python program!
You can also type Python code directly and see results instantly. Just type python in the terminal and start typing commands one at a time. This is great for
quick testing.
3. Variables and Data Types
What is a Variable?
A variable is like a labeled box where you store information. You give the box a name, and you can put a value inside it, and change that value later.
name = "Ravi"
age = 25
height = 5.9
is_student = True
In Python, you don't need to say what type of data a variable will hold - Python figures it out automatically. This is called dynamic typing.
x = 10
print(type(x))
Type Conversion
a = "10"
b = int(a) # converts string to integer
c = float(b) # converts integer to float
d = str(c) # converts float back to string
print(b, c, d)
Easy Tip: Think of int() , float() , and str() as "converter machines" - you feed a value in, and it comes out in the new type.
4. Operators
Arithmetic Operators
+ Addition 5+3 8
- Subtraction 5-3 2
* Multiplication 5*3 15
** Exponent (power) 5 ** 2 25
Comparison Operators
Logical Operators
and True if both conditions are true (5 > 3) and (2 > 1) → True
Assignment Operators
x = 10
x += 5 # same as x = x + 5, now x = 15
x -= 3 # x = 12
x *= 2 # x = 24
x //= 5 # x = 4
Practice: Try predicting the output of 17 % 5 and 17 // 5 before running the code. This helps you understand the difference between modulus and floor division.
5. Strings in Detail
What is a String?
A string is simply text, written inside single quotes '...' or double quotes "..." .
word = "PYTHON"
print(word[0]) # P
print(word[-1]) # N (last character)
print(word[0:3]) # PYT (slicing: start to end-1)
print(word[::-1]) # NOHTYP (reversed string)
Easy Way to Remember: Strings in Python are like a row of connected beads. Each bead has a position number, and you can pick, cut, or rearrange them using indexing
and slicing.
6. Lists
What is a List?
A list is an ordered collection of items that can be changed (mutable) after creation. Lists can hold different types of data together.
print(fruits[0]) # apple
print(fruits[-1]) # cherry
print(fruits[1:3]) # ['banana', 'cherry']
Remember: Lists are mutable, meaning you can add, remove, or change items after the list is created. Use square brackets [ ] for lists.
7. Tuples
What is a Tuple?
A tuple is just like a list, but it is immutable - once created, you cannot change, add, or remove items. Tuples use round brackets ( ) .
print(coordinates[0]) # 10
x, y = coordinates # unpacking a tuple
print(x, y) # 10 20
Easy Analogy: A list is like a whiteboard - you can erase and rewrite. A tuple is like a printed page - once written, it stays the same.
8. Sets
What is a Set?
A set is an unordered collection of unique items. Duplicate values are automatically removed.
numbers = {1, 2, 2, 3, 3, 3}
print(numbers) # {1, 2, 3}
a = {1, 2, 3}
b = {2, 3, 4}
print([Link](b)) # {1, 2, 3, 4}
print([Link](b)) # {2, 3}
print([Link](b)) # {1}
[Link](5) # add an item
[Link](1) # remove an item
Real-Life Use: Sets are perfect when you want to remove duplicate entries, like getting a list of unique visitors to a website.
9. Dictionaries
What is a Dictionary?
A dictionary stores data as key-value pairs. Instead of accessing items by position (like lists), you access them by their key - similar to looking up a word in a
real dictionary.
student = {
"name": "Ravi",
"age": 25,
"course": "Computer Science"
}
print(student["name"]) # Ravi
student["age"] = 26 # update value
student["grade"] = "A" # add new key-value pair
del student["course"] # remove a key
Easy Analogy: Think of a dictionary as a phone contact list - you look up a name (key) to find the phone number (value), not the other way around.
10. Conditional Statements
Conditional statements let your program make decisions, just like a human would.
age = 20
Output: Adult
Indentation Matters!
Unlike many languages that use curly braces { } , Python uses indentation (spaces) to define blocks of code. This is not optional - incorrect indentation causes
errors.
Rule of Thumb: Always use 4 spaces for each level of indentation, and be consistent throughout your code.
Used to repeat an action for each item in a sequence (list, string, range, etc.)
for i in range(5):
print(i)
Output: 0 1 2 3 4
count = 0
while count < 5:
print(count)
count += 1
Keyword Purpose
for i in range(10):
if i == 5:
break # stop loop when i is 5
if i % 2 == 0:
continue # skip even numbers
print(i)
Easy Analogy: A for loop is like reading every page of a book one by one. A while loop is like reading pages until you get tired (condition becomes false).
12. Functions
What is a Function?
A function is a reusable block of code that performs a specific task. Instead of writing the same code again and again, you write it once inside a function and call it
whenever needed.
def greet(name):
print("Hello, " + name + "!")
greet("Ravi")
greet("Anita")
Return Values
result = add(5, 3)
print(result) # 8
Default Parameters
def greet(name="Guest"):
print("Hello, " + name)
Keyword Arguments
Why Use Functions? Functions make your code organized, reusable, and easier to debug. Instead of repeating code, you write it once and call it many times.
13. Lambda Functions & map/filter/reduce
Lambda Functions
A lambda function is a small, anonymous (unnamed) function written in a single line. It is useful for short, simple operations.
square = lambda x: x * x
print(square(5)) # 25
add = lambda a, b: a + b
print(add(3, 4)) # 7
numbers = [1, 2, 3, 4]
squared = list(map(lambda x: x * x, numbers))
print(squared) # [1, 4, 9, 16]
numbers = [1, 2, 3, 4, 5, 6]
evens = list(filter(lambda x: x % 2 == 0, numbers))
print(evens) # [2, 4, 6]
numbers = [1, 2, 3, 4]
total = reduce(lambda a, b: a + b, numbers)
print(total) # 10
Easy Analogy: map transforms every item, filter picks only the items you want, and reduce squashes everything into one final answer.
14. Comprehensions
List Comprehension
# Normal way
squares = []
for x in range(5):
[Link](x * x)
With a Condition
Dictionary Comprehension
Set Comprehension
Practice: Rewrite this loop as a list comprehension: result = []; for x in range(20): if x % 3 == 0: [Link](x)
15. String Formatting
name = "Ravi"
age = 25
print(f"My name is {name} and I am {age} years old.")
Formatting Numbers
price = 49.99999
print(f"Price: {price:.2f}") # Price: 50.00
number = 1000000
print(f"{number:,}") # 1,000,000
# .format() method
print("My name is {} and I am {} years old.".format(name, age))
Best Practice: Always prefer f-strings in modern Python - they are faster, cleaner, and easiest to read.
16. File Handling
Using with automatically closes the file for you, even if an error occurs. This is the recommended way.
File Modes
Mode Meaning
Writing to a File
Tip: Always use with open(...) instead of manually calling open() and close() . It prevents accidental file corruption or memory leaks.
17. Exception Handling
Sometimes your program runs into unexpected problems, like dividing by zero or trying to open a file that doesn't exist. Instead of crashing, we can "catch" these
errors gracefully.
try:
result = 10 / 0
except ZeroDivisionError:
print("You can't divide by zero!")
else:
print("Division successful:", result)
finally:
print("This always runs, no matter what.")
Output: You can't divide by zero! This always runs, no matter what.
try:
num = int(input("Enter a number: "))
result = 10 / num
except ValueError:
print("That's not a valid number!")
except ZeroDivisionError:
print("Cannot divide by zero!")
def check_age(age):
if age < 0:
raise ValueError("Age cannot be negative!")
return age
Easy Analogy: Think of try/except like wearing a seatbelt - you hope you never need it, but if something goes wrong, it protects your program from crashing.
18. Object-Oriented Programming (OOP)
What is OOP?
Object-Oriented Programming is a way of organizing code around objects (real-world things) instead of just functions and logic. Each object is created from a
class, which acts like a blueprint.
class Dog:
def __init__(self, name, breed):
[Link] = name
[Link] = breed
def bark(self):
print(f"{[Link]} says Woof!")
__init__ is a special method called a constructor - it runs automatically when a new object is created, to set up its initial values. self refers to the current
object itself.
1. Encapsulation
Bundling data and methods together inside a class, and restricting direct access to some details.
class BankAccount:
def __init__(self, balance):
self.__balance = balance # double underscore = private variable
def get_balance(self):
return self.__balance
account = BankAccount(1000)
[Link](500)
print(account.get_balance()) # 1500
2. Inheritance
Allows a class to inherit properties and methods from another class, avoiding repeated code.
class Animal:
def __init__(self, name):
[Link] = name
def speak(self):
print(f"{[Link]} makes a sound.")
c = Cat("Whiskers")
[Link]() # Whiskers says Meow!
3. Polymorphism
Different classes can define the same method name, but each behaves differently.
class Dog:
def speak(self):
print("Woof!")
class Cat:
def speak(self):
print("Meow!")
for animal in [Dog(), Cat()]:
[Link]() # each object responds in its own way
4. Abstraction
Hiding complex implementation details and showing only the essential features.
class Shape(ABC):
@abstractmethod
def area(self):
pass
class Circle(Shape):
def __init__(self, radius):
[Link] = radius
def area(self):
return 3.14 * [Link] ** 2
c = Circle(5)
print([Link]()) # 78.5
Easy Analogy: A class is like a cookie cutter, and objects are the cookies made from it. Each cookie (object) can have its own toppings (data), but they all share the same
shape (structure) from the cutter (class).
19. Modules and Packages
What is a Module?
A module is simply a Python file (.py) containing code - functions, classes, or variables - that you can reuse in other programs.
import math
print([Link](16)) # 4.0
print([Link]) # 3.14159...
import random
print([Link](1, 10)) # random number between 1 and 10
# [Link]
def add(a, b):
return a + b
import mymath
print([Link](3, 4)) # 7
What is a Package?
A package is simply a folder containing multiple related modules, along with a special __init__.py file. It helps organize large projects.
20. Iterators and Generators
What is an Iterator?
An iterator is an object that lets you go through a collection of items one at a time, using next() .
numbers = [1, 2, 3]
it = iter(numbers)
print(next(it)) # 1
print(next(it)) # 2
print(next(it)) # 3
What is a Generator?
A generator is a special type of function that produces values one at a time, instead of returning them all at once. It uses yield instead of return , which makes
it very memory-efficient for large data.
def count_up_to(n):
count = 1
while count <= n:
yield count
count += 1
Output: 1 2 3 4 5
Easy Analogy: A regular function is like handing someone a full basket of fruit all at once. A generator is like handing them one fruit at a time, only when they ask for it -
saving memory and effort.
Generator Expressions
What is a Decorator?
A decorator is a function that "wraps" another function to add extra functionality, without changing the original function's code.
def my_decorator(func):
def wrapper():
print("Something happens before the function runs.")
func()
print("Something happens after the function runs.")
return wrapper
@my_decorator
def say_hello():
print("Hello!")
say_hello()
Output: Something happens before the function runs. Hello! Something happens after the function runs.
import time
def timer(func):
def wrapper(*args, **kwargs):
start = [Link]()
result = func(*args, **kwargs)
end = [Link]()
print(f"{func.__name__} took {end - start:.4f} seconds")
return result
return wrapper
@timer
def slow_function():
[Link](1)
slow_function()
Easy Analogy: A decorator is like a gift wrapper - it doesn't change what's inside the box (the function), but it adds something extra around it (new behavior).
22. Regular Expressions
A regular expression (regex) is a pattern used to search, match, or manipulate text. Python's re module handles this.
import re
Symbol Meaning
\s Any whitespace
^ Start of string
$ End of string
Useful Functions
now = [Link]()
print(now) # current date & time
print([Link], [Link], [Link]) # individual parts
Formatting Dates
Code Meaning
%Y 4-digit year
%m Month (01-12)
%d Day (01-31)
%M Minutes
%S Seconds
def add_all(*args):
return sum(args)
print(add_all(1, 2, 3)) # 6
print(add_all(1, 2, 3, 4, 5)) # 15
def print_info(**kwargs):
for key, value in [Link]():
print(f"{key}: {value}")
Easy Analogy: *args is like a bag that collects extra plain items, and **kwargs is like a bag that collects extra labeled items (key-value pairs).
25. Context Managers (with statement)
Context managers handle setup and cleanup automatically, such as opening and closing files, or connecting and disconnecting from a database. We've already
seen this with file handling.
class MyContext:
def __enter__(self):
print("Entering the context")
return self
def __exit__(self, exc_type, exc_val, exc_tb):
print("Exiting the context")
Output: Entering the context Inside the block Exiting the context
@contextmanager
def my_context():
print("Start")
yield
print("End")
with my_context():
print("Doing work")
26. Working with JSON
What is JSON?
JSON (JavaScript Object Notation) is a lightweight format for storing and exchanging data. It looks very similar to Python dictionaries, which makes it easy to work
with.
import json
# Writing
with open("[Link]", "w") as f:
[Link](data, f)
# Reading
with open("[Link]", "r") as f:
loaded_data = [Link](f)
27. Multithreading and Multiprocessing (Intro)
Normally, Python runs code line by line, one task at a time. Multithreading and multiprocessing let you run multiple tasks at (nearly) the same time - useful for
speeding up programs that wait a lot (like downloading files) or that do heavy computation.
Multithreading Example
Best for tasks that involve waiting, like network requests or file downloads.
import threading
import time
def print_numbers():
for i in range(5):
print(i)
[Link](1)
t1 = [Link](target=print_numbers)
[Link]()
[Link]() # wait for thread to finish
Multiprocessing Example
Best for CPU-heavy tasks, like large calculations, since it uses multiple CPU cores.
def square(n):
print(n * n)
p1 = Process(target=square, args=(5,))
[Link]()
[Link]()
Simple Rule: Use threading for tasks that involve waiting (I/O-bound), and multiprocessing for tasks that involve heavy calculations (CPU-bound).
28. Virtual Environments and pip
What is pip?
pip is Python's package manager - it lets you install extra libraries that aren't built into Python.
A virtual environment is an isolated space for a specific project, so that its packages don't conflict with other projects on your computer.
# Activate it (Windows)
myenv\Scripts\activate
# Activate it (Mac/Linux)
source myenv/bin/activate
Easy Analogy: A virtual environment is like having a separate toolbox for each project, so tools from one project never get mixed up with another.
[Link]
This file lists all the packages a project needs, so others can install them easily.
What is PEP 8?
PEP 8 is the official style guide for writing clean, readable Python code. Following it makes your code easier for others (and yourself) to understand.
Key Guidelines
# Bad
def f(x,y):
return x+y
# Good
def add_numbers(first_number, second_number):
"""Returns the sum of two numbers."""
return first_number + second_number
Tip: Tools like black and flake8 can automatically check and format your code to follow PEP 8 standards.
30. Mini Project: Putting It All Together
This mini project uses variables, dictionaries, functions, loops, conditionals, file handling, and exception handling - combining everything you've learned.
import json
def load_contacts():
try:
with open("[Link]", "r") as f:
return [Link](f)
except FileNotFoundError:
return {}
def save_contacts(contacts):
with open("[Link]", "w") as f:
[Link](contacts, f, indent=2)
def add_contact(contacts):
name = input("Enter name: ")
phone = input("Enter phone number: ")
contacts[name] = phone
save_contacts(contacts)
print(f"{name} added successfully!")
def view_contacts(contacts):
if not contacts:
print("No contacts found.")
for name, phone in [Link]():
print(f"{name}: {phone}")
def main():
contacts = load_contacts()
while True:
print("\n1. Add Contact\n2. View Contacts\n3. Exit")
choice = input("Choose an option: ")
if choice == "1":
add_contact(contacts)
elif choice == "2":
view_contacts(contacts)
elif choice == "3":
print("Goodbye!")
break
else:
print("Invalid choice, try again.")
if __name__ == "__main__":
main()
What This Project Teaches: Functions for organization, dictionaries for data storage, JSON for saving data permanently, loops for repeated menus, conditionals for
decision-making, and the if __name__ == "__main__": pattern, which ensures code only runs when the file is executed directly (not when imported).
Congratulations!
You have now covered Python from the very basics all the way to advanced concepts like decorators, generators, and multithreading. The best way to truly learn
programming is by writing code yourself - so open your editor, and start building small projects using what you've learned here. Practice consistently, be patient
with mistakes, and enjoy the process!