Python
Python is a high-level, interpreted, object-oriented programming language developed by Guido van Rossum in 1991.
print(“Hello, World!”)
Modules, Comments and Pip:
Modules in Python:
A module is a file containing Python code that can be reused.
Types of Modules in Python:
Python modules are mainly classified into 3 types:
1. Built-in Modules (Predefined Modules)
These modules come already installed with Python.
You don’t need to install them separately.
Examples
mathrandomdatetimeossys
User-Defined Modules
Modules created by programmers according to their needs.
Step 1: Create a file named calculator.py
Step 2: Use the module
External Modules or Third-Party Modules
Modules developed by other programmers and installed using pip.
Examples
numpypandasmatplotlibtensorflowrequests
COMMENTS
Comments are notes written for programmers.
TYPES OF COMMENTS
1] Single Line Comment (#)
2] Multi Line Comment ( ‘’’ ‘’’)
PIP(Preferred Installer Program)
PIP is Python’s package manager.
Think of it as:
Play Store for Python
Just as Play Store installs apps,
PIP installs Python packages.
Variables, Data Types, Keywords & Operators
Variables store data values.
name = “Subashini”
age = 21
print(name)
print(age)
Identifiers are names used for variables, functions, classes, etc.
Valid Identifiers:
student_name = “Suba”
_age = 21
marks1 = 95
Invalid Identifiers:
1name = “Suba”
class = “Python”
Data Types in Python
Integer:
An Integer is a data type used to store whole numbers without any decimal point.
x = 10
print(type(x))
Float:
A Float is a data type used to store decimal numbers (floating-point numbers).
y = 10.5
print(type(y))
String:
A String is a sequence of characters enclosed within single quotes (' ') or double quotes (" ").
name = “Python”
print(type(name))
Boolean:
A Boolean is a data type that can store only two values: True or False.
flag = True
print(type(flag))
List:
A list is an ordered, mutable collection.
lst = [1,2,3]
Tuple:
An ordered and immutable collection.
t = (1,2,3)
Set:
An unordered collection of unique elements.
s = {1,2,3}
Dictionary:
Stores data as key-value pairs.
d = {“name”:”Suba”}
FLOW CONTROL:
Flow control determines the order in which statements are executed in a program.
print(“Statement 1”)
print(“Statement 2”)
print(“Statement 3”)
The statements execute one after another.
Sometimes we need to make decisions based on conditions. That’s where flow control comes in.
If Statement:
The if statement is used to execute a block of code only when a condition is True.
Syntax:
if condition:
statement
If-Else Statement:
The if-else statement executes one block when the condition is True and another block when it is False.
if condition:
statement1
else:
statement2
Elif Statement
elif means "else if".
It is used when multiple conditions need to be checked.
if condition1:
statement
elif condition2:
statement
else:
statement
Nested If Statement:
An if statement inside another if statement is called a Nested If.
if condition1:
# Outer if block
if condition2:
# Inner if block
statements
LOOPS:
A loop is used to execute a block of code repeatedly.
Why Loops?
Without loop:
print(“Hello”)
print(“Hello”)
print(“Hello”)
print(“Hello”)
print(“Hello”)
With loop:
for i in range(5):
print(“Hello”)
While Loop
A while loop executes as long as the condition remains True.
Syntax:
while condition:
statement
Example:
i = 1
while i <= 5:
print(i)
i += 1
For Loop:
A for loop is used to iterate through a sequence such as a list, tuple, string, or range.
for i in [10,20,30]:
print(i)
For Loop Using range():
The range() function generates a sequence of numbers.
for i in range(1,6):
print(i)
Types of range():
range(stop)
Output: 0 1 2 3 4
range(start, stop)
range(1,5)
Output: 1 2 3 4
range(start, stop, step)
range(1,10,2)
Output: 1 3 5 7 9
Nested For Loop:
A for loop inside another for loop is called a Nested For Loop.
for i in range(3):
for j in range(2):
print(i, j)
Output:
0 0
0 1
1 0
1 1
2 0
2 1
STRINGS:
A string is a sequence of characters enclosed within single quotes or double quotes.
name = “Python”
Creating Strings in Python:
Using Single Quotes, Double Quotes, Triple Quotes.
String Indexing and Slicing:
Indexing:
Each character has a position.
P Y T H O N
0 1 2 3 4 5
Example:
name = “PYTHON”
print(name[0])
Output: P
Negative Indexing:
P Y T H O N
-6 -5 -4 -3 -2 -1
print(name[-1])
Output: N
Slicing
Used to extract a portion of a string.
name = “PYTHON”
print(name[0:3])
Output: PYT
Deleting the String:
Deleting means removing the entire string variable from memory.
Example:
name = “Python”
del name
After deletion:
print(name)
Output: NameError
String Formatting:
String formatting is the process of inserting values into a string.
Method 1: Using f-string (Most Common)
name = “Subashini”
age = 21
print(f”My name is {name} and I am {age} years old.”)
Output:
My name is Subashini and I am 21 years old.
Method 2: Using format()
name = “Subashini”
print(“My name is {}”.format(name))
Method 3: Using % Operator
name = “Subashini”
print(“My name is %s” % name)
FUNCTIONS:
A function is a block of code that performs a specific task and can be reused whenever needed.
Why Functions?
Without functions:
print(“Welcome”)
print(“Welcome”)
print(“Welcome”)
With functions:
def greet():
print(“Welcome”)
greet()
greet()
greet()
Creating a Function & Function Calling:
Syntax:
def function_name():
statements
function_name()
Example:
def greet():
print(“Hello”)
greet()
Output: Hello
Function with Parameters:
def add(a, b):
print(a+b)
add(10, 20)
# a,b → Parameters
# 10,20 → Arguments
Output:
30
Return Statement:
The return statement sends a value back to the place where the function was called.
Syntax:
def function_name():
return value
Difference Between print() and return:
print() - Cannot store the result.
return - Can store and reuse the result.
Scope of Variables
Scope determines where a variable can be accessed.
Local Variable:
Created inside a function.
def display():
x = 10
print(x)
display()
Global Variable:
Created outside a function.
x = 10
def display():
print(x)
display()
FILE HANDLING:
Introduction to File Input/Output
File handling allows us to store and retrieve data permanently.
Why File Handling?
Without file:
Program Ends
↓
Data Lost
With file:
Program Ends
↓
Data Saved
Types of Files
Text Files:
Store human-readable data.
Eg: notes.txt
students.txt
data.csv
Binary Files:
Store data in machine-readable format.
Eg: image.jpg
audio.mp3
video.mp4
Opening and Closing Files
Opening a File:
Syntax: file = open(“filename”,”mode”)
Eg: file = open(“data.txt”,”r”)
Closing a File:
Syntax: file.close()
Eg: file = open(“data.txt”,”r”)
file.close()
Reading and Writing Text Files
Writing:
file = open(“data.txt”,”w”)
file.write(“Hello Python”)
file.close()
Reading:
file = open(“data.txt”,”r”)
Get Subashini Mannuraja’s stories in your inbox
Join Medium for free to get updates from this writer.
print(file.read())
file.close()
Read Methods
read()
Reads entire file.
file.read()
readline()
Reads one line.
file.readline()
readlines()
Reads all lines into a list.
file.readlines()
Working with Binary Files:
Binary files store data as bytes rather than text.
Examples: Images
Videos
Audio Files
PDF Files
Writing Binary Data:
file = open(“image.jpg”,”wb”)
Reading Binary Data:
file = open(“image.jpg”,”rb”)
Exception Handling in File Operations
Problem:
If file doesn’t exist:
file = open(“abc.txt”,”r”)
Output: FileNotFoundError
Solution:
try:
file = open(“abc.txt”,”r”)
print(file.read())
except FileNotFoundError:
print(“File not found”)
Output: File not found
EXCEPTION HANDLING:
Exception handling is a mechanism used to handle runtime errors without terminating the program.
Example: print(10/0)
Output: ZeroDivisionError
With Exception Handling:
try:
print(10/0)
except:
print(“Error occurred”)
Output:
Error occurred.
Exception Handling Mechanism:
Syntax:
try:
risky code
except:
error handling code
Flow:
Try Block
↓
Exception?
↓ ↓
No Yes
↓ ↓
Run Except Block
Handling Multiple Exceptions:
Different exceptions can be handled separately.
Example:
try:
num = int(input())
print(10/num)
except ValueError:
print(“Invalid Input”)
except ZeroDivisionError:
print(“Cannot divide by zero”)
Custom Exceptions:
User-defined exceptions created using classes.
Syntax: class MyException(Exception):
pass
Error Handling Strategies
- Try-Except
try:
risky code
except:
handling code
Try-Except-Else
else runs when no exception occurs.
try:
x = 10/2
except:
print(“Error”)
else:
print(“Success”)
Try-Except-Finally
finally always executes.
try:
file = open(“data.txt”)
except:
print(“Error”)
finally:
print(“Closing file”)
FUNCTIONAL PROGRAMMING:
Functional Programming is a programming style where functions are treated as the main building blocks of a program.
Instead of repeatedly writing loops, we use functions to process data.
Benefits
- Cleaner code
- Less code
- Easier maintenance
- Better readability
map():
map() applies a function to every element of an iterable (list, tuple, etc.).
Syntax: map(function, iterable)
Example:
Without map():
nums = [1,2,3,4]
result = []
for i in nums:
result.append(i*2)
print(result)
With map():
nums = [1,2,3,4]
result = list(map(lambda x:x*2, nums))
print(result)
Output:
[2,4,6,8]
Eg: Teacher adds 5 grace marks to every student’s mark.
80 → 85
70 → 75
60 → 65
Map modifies every item.
filter():
Filter selects elements that satisfy a condition.
Syntax:
filter(function, iterable)
Example:
nums = [1,2,3,4,5,6]
result = list(filter(lambda x:x%2==0, nums))
print(result)
Output:
[2,4,6]
Eg: Selecting only students who passed.
Marks:
90
45
80
30
Result:
90
80
reduce():
Reduce combines all elements into a single value.
Syntax:
from functools import reduce
Example:
from functools import reduce
nums = [1,2,3,4]
result = reduce(lambda x,y:x+y, nums)
print(result)
Output: 10
Eg: Adding total marks of all subjects.
80 + 90 + 70 + 60 = 300
Lambda Functions:
A Lambda Function is an anonymous function (function without a name).
Syntax: lambda arguments : expression
Example: square = lambda x:x*x
print(square(5))
Output: 25
Equivalent Normal Function:
def square(x):
return x*x
Why Lambda?
Used for short operations.
Especially with:
- map()
- filter()
- reduce()
WORKING WITH FILES AND DIRECTORIES:
File Handling: File handling is used to store data permanently.
Without files:
Program Ends
↓
Data Lost
With files:
Program Ends
↓
Data Saved
Binary Files: Binary files store information as bytes.
Eg: image.jpg
video.mp4
audio.mp3
document.pdf
Reading Binary Files:
file = open(“image.jpg”,”rb”)
data = file.read()
file.close()
Writing Binary Files:
file = open(“copy.jpg”,”wb”)
file.write(data)
file.close()
Directory Manipulation:
Directory manipulation means working with folders.
Python uses the os module.
Create Folder:
import os
os.mkdir(“Projects”)
Delete Folder:
os.rmdir(“Projects”)
Rename Folder:
os.rename(“Old”,”New”)
Current Working Directory:
os.getcwd()
Real-Life Example:
Same as creating, deleting, and renaming folders in Windows.
CSV Files:
CSV stands for Comma Separated Values
Eg: Name,Age
Subashini,21
Priya,20
Reading CSV:
import csv
with open(“students.csv”,”r”) as file:
reader = csv.reader(file)
for row in reader:
print(row)
Writing CSV:
import csv
with open(“students.csv”,”w”) as file:
writer = csv.writer(file)
writer.writerow([“Name”,”Age”])
JSON Files:
JSON stands for JavaScript Object Notation
Used for data exchange between applications.
Example JSON:
{
“name”:”Subashini”,
“age”:21
}
Reading JSON:
import json
with open(“data.json”,”r”) as file:
data = json.load(file)
print(data)
Eg: When a website sends user information to a server, JSON is commonly used.
REGULAR EXPRESSIONS (REGEX)
Regex (Regular Expression) is a sequence of characters used to search, match, validate, or replace text patterns.
Python uses the re module.
import re
Why Regex?
Suppose you need to validate:
- Email addresses
- Phone numbers
- Passwords
Regex makes it easy.
Introduction to Regex:
import re
text = “Python”
result = re.search(“Py”, text)
print(result)
Output: Match Found
Pattern Matching using re Module:
search()
Finds first occurrence.
re.search(“cat”,”The cat is sleeping”)
findall()
Returns all matches.
re.findall(“cat”,”cat dog cat”)
Output:
[‘cat’,’cat’]
match()
Checks from the beginning of the string.
re.match(“Hello”,”Hello World”)
sub()
Replaces text.
re.sub(“cat”,”dog”,”cat is sleeping”)
Output:
dog is sleeping
Common Regex Patterns
Digits:
\d
Matches:
0–9
Example:
re.findall(r”\d”,”A1B2C3")
Output:
[‘1’, ‘2’, ‘3’]
Alphabets:
[a-z]
Matches lowercase letters.
Uppercase Letters:
[A-Z]
Matches uppercase letters.
Any Character
.
Matches any single character.
One or More Occurrences
+
Example:
a+
Matches:
a
aa
aaa
Beginning of String:
^
Example:
^Hello
String must start with Hello.
End of String:
$
Example:
World$
String must end with World.




