PYTHON PROGRAMMING
Complete Notes — Fundamentals to Advanced
Python is a high-level, interpreted, general-purpose programming language known for its simplicity,
readability, and vast ecosystem. This document covers core Python concepts from variables and data
types through object-oriented programming, file handling, and popular libraries.
1. Introduction to Python
Python was created by Guido van Rossum and first released in 1991. It emphasizes code readability and
a clean syntax that allows programmers to express concepts in fewer lines compared to languages like
C++ or Java.
1.1 Key Features
• Interpreted language — no compilation step needed
• Dynamically typed — variable types resolved at runtime
• Object-Oriented, Functional, and Procedural support
• Huge standard library and third-party ecosystem (PyPI)
• Platform independent — runs on Windows, Linux, macOS
1.2 Python Versions
Python 3.x is the current and actively supported version. Python 2.x reached end-of-life in January 2020.
Always use Python 3.10+ for new projects.
Note: Check your version with: python --version
2. Variables & Data Types
Variables in Python are dynamically typed. You do not need to declare a type; the interpreter infers it at
runtime.
2.1 Primitive Types
# Integer
age = 25
# Float
pi = 3.14159
# String
name = 'Alice'
# Boolean
is_active = True
# NoneType
result = None
2.2 Type Casting
x = int('42') # 42
y = float('3.14') # 3.14
z = str(100) # '100'
b = bool(0) # False
2.3 Multiple Assignment
a, b, c = 1, 2, 3
x = y = z = 0
Note: Python identifiers are case-sensitive. my_var and My_Var are different.
3. Strings
Strings in Python are immutable sequences of Unicode characters. Python provides a rich set of built-in
string methods.
3.1 String Operations
s = 'Hello, World!'
print(s[0]) # H
print(s[-1]) # !
print(s[0:5]) # Hello
print(len(s)) # 13
print([Link]()) # HELLO, WORLD!
print([Link]('World','Python'))
3.2 f-Strings (Formatted Literals)
name = 'Bob'
score = 95.5
print(f'{name} scored {score:.1f}%')
3.3 Useful String Methods
• strip(), lstrip(), rstrip() — remove whitespace
• split(sep) — split into list
• join(iterable) — join list into string
• find(sub), count(sub) — search within string
• startswith(), endswith() — prefix/suffix check
4. Collections
4.1 Lists
Lists are mutable, ordered sequences that allow duplicate elements.
fruits = ['apple','banana','cherry']
[Link]('mango')
[Link]('banana')
print(fruits[1:3]) # ['cherry', 'mango']
4.2 Tuples
Tuples are immutable ordered sequences. Use them for fixed data.
coords = (10.5, 20.3)
x, y = coords # unpacking
4.3 Dictionaries
Dictionaries store key-value pairs. Keys must be hashable (usually strings or numbers).
student = {'name':'Alice', 'age':21, 'grade':'A'}
student['email'] = 'alice@[Link]'
for key, val in [Link]():
print(f'{key}: {val}')
4.4 Sets
s = {1, 2, 3, 2, 1} # {1, 2, 3} — no duplicates
[Link](4)
print(2 in s) # True
5. Control Flow
5.1 if / elif / else
score = 78
if score >= 90:
grade = 'A'
elif score >= 75:
grade = 'B'
else:
grade = 'C'
print(grade) # B
5.2 for Loops
for i in range(1, 6):
print(i, end=' ') # 1 2 3 4 5
for fruit in ['apple','mango']:
print(fruit)
5.3 while Loops
n = 10
total = 0
while n > 0:
total += n
n -= 1
print(total) # 55
5.4 List Comprehensions
squares = [x**2 for x in range(1,11)]
evens = [x for x in range(20) if x%2==0]
6. Functions
Functions are defined with the def keyword and can accept default arguments, *args, and **kwargs.
def greet(name, greeting='Hello'):
return f'{greeting}, {name}!'
print(greet('Alice')) # Hello, Alice!
print(greet('Bob','Hi')) # Hi, Bob!
def total(*nums):
return sum(nums)
print(total(1,2,3,4)) # 10
6.1 Lambda Functions
square = lambda x: x**2
double = lambda x: x*2
print(square(5)) # 25
6.2 Scope — LEGB Rule
• L — Local scope (inside function)
• E — Enclosing scope (nested functions)
• G — Global scope (module level)
• B — Built-in scope (Python built-ins)
Note: Use global keyword to modify a global variable inside a function.
7. Object-Oriented Programming
class Animal:
def __init__(self, name, sound):
[Link] = name
[Link] = sound
def speak(self):
return f'{[Link]} says {[Link]}'
class Dog(Animal):
def fetch(self):
return f'{[Link]} fetches the ball!'
dog = Dog('Rex', 'Woof')
print([Link]()) # Rex says Woof
print([Link]()) # Rex fetches the ball!
7.1 Magic Methods
• __init__ — constructor
• __str__ — string representation
• __len__ — length operator
• __eq__, __lt__ — comparison operators
8. File Handling & Modules
# Write to file
with open('[Link]', 'w') as f:
[Link]('Hello\nWorld')
# Read from file
with open('[Link]', 'r') as f:
content = [Link]()
print(content)
8.1 Exception Handling
try:
result = 10 / 0
except ZeroDivisionError as e:
print(f'Error: {e}')
finally:
print('Done')
8.2 Popular Libraries
• numpy — numerical computing and arrays
• pandas — data manipulation and analysis
• matplotlib / seaborn — data visualization
• requests — HTTP requests
• Flask / FastAPI / Django — web frameworks
• scikit-learn — machine learning
Python's versatility makes it the #1 choice for data science, automation, web development, and AI/ML
applications worldwide.