Python Programming Bootcamp
Python Programming Bootcamp
PYTHON PROGRAMMING
Learn • Practice • Build
Begin your programming journey with one of the world's most powerful
INSTRUCTOR EDITION
Mohanraj R
Python Trainer | AI & ML Enthusiast
mohanraj9677011@[Link]
[Link]/in/moganraj | [Link]/lookmohan
June 2026
Page 1
Python Programming Mohanraj R
TABLE OF CONTENTS
Page 2
Python Programming Mohanraj R
What is Python?
Python is a high-level, interpreted, open-source programming language. It is easy to read, beginner-friendly, and
widely used in web development, data science, AI, and automation.
Python Features
• Open source and free to use
• Easy to read and understand
• High-level programming language
• Interpreted language — executes line by line
• Supports Object-Oriented Programming (OOP)
Data Types
A data type tells Python what kind of value a variable holds.
Data Type Keyword Example
Integer int 1, 2, 100
String str 'hello', "world"
Float float 3.14, 1.0
Boolean bool True, False
Variables
A variable is a container that stores a value.
Comments
Comments are lines Python ignores. They help explain code.
Page 3
Python Programming Mohanraj R
"""
This is a
multi-line comment
"""
Page 4
Python Programming Mohanraj R
# Integer to Float
a = 10
b = float(a)
print(b) # Output: 10.0
# Integer to String
a = 50
b = str(a)
print(b) # Output: '50'
Note: int() removes the decimal part. It does NOT round the number. 10.9 becomes 10.
Page 5
Python Programming Mohanraj R
Page 6
Python Programming Mohanraj R
Chapter 04 — Operators
1. Arithmetic Operators
print(10 + 3) # Addition -> 13
print(10 - 3) # Subtraction -> 7
print(10 * 3) # Multiplication -> 30
print(10 / 3) # Division -> 3.333...
print(10 // 3) # Floor Division -> 3
print(10 % 3) # Modulus -> 1 (remainder)
print(2 ** 3) # Exponent -> 8 (2 to the power 3)
2. Assignment Operators
x = 10
x += 5 # x = x + 5 -> 15
x -= 3 # x = x - 3 -> 12
x *= 2 # x = x * 2 -> 24
x //= 4 # x = x // 4 -> 6
3. Comparison Operators
Always returns True or False.
print(5 == 5) # Equal -> True
print(5 != 3) # Not equal -> True
print(5 > 3) # Greater than -> True
print(5 < 3) # Less than -> False
print(5 >= 5) # Greater or equal -> True
print(5 <= 4) # Less or equal -> False
4. Logical Operators
print(True and True) # Both must be True -> True
print(True and False) # One is False -> False
print(True or False) # At least one True -> True
print(not True) # Reverses result -> False
5. Identity Operators
a = [1, 2, 3]
b = a
c = [1, 2, 3]
print(a is b) # True — same object in memory
print(a is c) # False — different objects (same content)
print(a is not c) # True
6. Membership Operators
fruits = ["apple", "mango", "grape"]
print("mango" in fruits) # True
print("banana" in fruits) # False
print("banana" not in fruits) # True
7. Bitwise Operators
Work on binary (0s and 1s) representation of numbers.
Page 7
Python Programming Mohanraj R
Page 8
Python Programming Mohanraj R
if Statement
age = 20
if age >= 18:
print("Eligible to vote")
if-else Statement
number = int(input("Enter a number: "))
if number % 2 == 0:
print("Even number")
else:
print("Odd number")
if-elif-else Statement
Used when you need to check multiple conditions one after another.
mark = int(input("Enter your mark: "))
if mark >= 90:
print("Grade A")
elif mark >= 75:
print("Grade B")
elif mark >= 50:
print("Grade C")
elif mark >= 35:
print("Grade D")
else:
print("Fail")
Nested if Statement
An if-else placed inside another if or else block.
age = int(input("Enter age: "))
has_id = input("Do you have an ID? (yes/no): ")
Practice Questions
• 1. Check if a number is greater than 15
• 2. Check if a number is odd or even
• 3. Check if a number is positive or negative
• 4. Print student grade based on marks (A/B/C/D/Fail)
Page 9
Python Programming Mohanraj R
range() Function
# range(stop) — starts from 0
for i in range(5): # 0, 1, 2, 3, 4
print(i)
# range(start, stop)
for i in range(1, 6): # 1, 2, 3, 4, 5
print(i)
# Reverse
for i in range(10, 0, -1): # 10, 9, 8 ... 1
print(i)
Examples
# Multiplication table of 5
for i in range(1, 11):
print("5 x", i, "=", 5 * i)
# Sum from 1 to 10
total = 0
for i in range(1, 11):
total += i
print("Sum:", total) # 55
Page 10
Python Programming Mohanraj R
# Output:
# 1 1 1
# 2 2 2
# 3 3 3
# Triangle pattern
for i in range(1, 6):
for j in range(i):
print("*", end="")
print()
# Output:
# *
# * *
# * * *
# * * * *
# * * * * *
# Reverse triangle
for i in range(6, 0, -1):
for j in range(i):
print("*", end="")
print()
Practice Questions
• 1. Print numbers from 1 to 5
• 2. Print all even numbers from 1 to 20
• 3. Print all odd numbers from 1 to 20
• 4. Print multiplication table of a number entered by the user
• 5. Print your name four times using a loop
• 6. Find the sum of numbers from 1 to 100
• 7. Print square values from 1 to 10 (1, 4, 9, 16 ...)
• 8. Print a diamond pattern using nested loops
Page 11
Python Programming Mohanraj R
Page 12
Python Programming Mohanraj R
Types of Arguments
# 1. Positional Arguments — order matters
def student(name, age):
print(name, age)
student("Arun", 20)
Page 13
Python Programming Mohanraj R
# Regular function
def square(x):
return x * x
# Same as lambda
square = lambda x: x * x
print(square(5)) # Output: 25
Page 14
Python Programming Mohanraj R
Importing Modules
# 1. Normal import
import math
print([Link](25)) # 5.0
print([Link](5)) # 120
print([Link]) # 3.14159...
import datetime
now = [Link]()
print(now) # current date and time
import os
print([Link]()) # current working directory
Packages
A package is a folder containing multiple modules. It must have a file called __init__.py inside.
# Installing third-party packages using pip
# Run in terminal:
# pip install requests
import requests
response = [Link]("[Link]
print(response.status_code) # 200
Page 15
Python Programming Mohanraj R
print(word[0]) # p
print(word[2]) # t
print(word[-1]) # n (last character)
# Repetition
print("Hi " * 3) # Hi Hi Hi
# Length
name = "python"
print(len(name)) # 6
String Slicing
# Syntax: string[start : stop : step]
name = "python"
print(name[2:4]) # th
print(name[:4]) # pyth
print(name[2:]) # thon
print(name[::2]) # pto (every 2nd character)
print(name[::-1]) # nohtyp (REVERSE the string!)
Page 16
Python Programming Mohanraj R
Chapter 11 — Lists
List Operations
fruits = ["apple", "mango", "pineapple", "grape"]
# Add
[Link]("banana") # add at end
[Link](1, "watermelon") # add at index 1
# Remove
[Link]("mango") # remove by value
[Link](0) # remove by index
[Link]() # remove last item
# Update
fruits[0] = "kiwi"
# Sort
numbers = [3, 1, 4, 1, 5, 9]
[Link]()
print(numbers) # [1, 1, 3, 4, 5, 9]
[Link](reverse=True)
print(numbers) # [9, 5, 4, 3, 1, 1]
List Slicing
numbers = [10, 20, 30, 40, 50, 60]
print(numbers[1:4]) # [20, 30, 40]
print(numbers[:3]) # [10, 20, 30]
print(numbers[3:]) # [40, 50, 60]
print(numbers[::-1]) # [60, 50, 40, 30, 20, 10]
Page 17
Python Programming Mohanraj R
Practice Questions
• 1. Create a list of 5 colours
• 2. Print the first and last item
• 3. Add one new item and remove one item
• 4. Print all items using a for loop
• 5. Find the length of the list
• 6. Sort the list and print it
Page 18
Python Programming Mohanraj R
Chapter 12 — Tuples
a = (1, 2)
b = (3, 4)
print(a + b) # (1, 2, 3, 4)
Practice Questions
• 1. Create a tuple with 5 numbers
• 2. Print the first and last item
• 3. Find the length of the tuple
• 4. Try changing an item — observe the error
Page 19
Python Programming Mohanraj R
Chapter 13 — Sets
Set Operations
a = {1, 2, 3, 4, 5}
b = {4, 5, 6, 7, 8}
Page 20
Python Programming Mohanraj R
Chapter 14 — Dictionaries
print(student["name"]) # Dhanush
print([Link]("age")) # 20
print([Link]())
print([Link]())
print([Link]())
Modifying Dictionaries
student["blood_group"] = "B+" # Add new key
student["blood_group"] = "A+" # Update value
[Link]("dept") # Remove key
print(student)
Page 21
Python Programming Mohanraj R
def display(self):
print("Name:", [Link])
print("Age :", [Link])
s1 = Student("Ravi", 20)
s2 = Student("Priya", 21)
[Link]()
[Link]()
Note: __init__ is the constructor — it runs automatically when you create an object.
Inheritance
A child class inherits all properties and methods of a parent class.
# Single Inheritance
class Animal:
def speak(self):
print("Animal speaks")
class Dog(Animal):
def bark(self):
print("Dog barks")
d = Dog()
[Link]() # Inherited from Animal
[Link]() # Dog's own method
class Parent(Grandparent):
def b(self): print("Parent")
class Child(Parent):
def c(self): print("Child")
obj = Child()
obj.a() # from Grandparent
obj.b() # from Parent
obj.c() # own
Same method name, different behaviour depending on which class calls it.
class Animal:
def speak(self):
print("Some sound")
class Dog(Animal):
def speak(self): # overrides parent method
print("Woof!")
class Cat(Animal):
def speak(self): # overrides parent method
print("Meow!")
def show(self):
print("Mark:", self.__mark)
s = Student()
[Link]() # Works fine -> Mark: 95
# print(s.__mark) # Error! Cannot access directly
Page 23
Python Programming Mohanraj R
File Modes
Mode Symbol Description
Read r Open for reading (file
must exist)
Write w Create new file or
overwrite existing
Append a Add to end without
deleting existing content
Read+Write r+ Read and write (file must
exist)
File Operations
# 1. Write to a file
file = open("[Link]", "w")
[Link]("Hello, Python!")
[Link]()
# 3. Append data
file = open("[Link]", "a")
[Link]("\nNew line added")
[Link]()
# Write
with open("[Link]", "w") as file:
[Link]("Python is awesome!")
Page 24
Python Programming Mohanraj R
Page 25
Python Programming Mohanraj R
Common Exceptions
Exception Cause
ZeroDivisionError Division by zero
ValueError Invalid value e.g. int('abc')
TypeError Wrong data type in operation
IndexError List index out of range
KeyError Dictionary key not found
FileNotFoundError File does not exist
NameError Variable used before being defined
try-except Syntax
try:
num = int(input("Enter a number: "))
print(10 / num)
except ZeroDivisionError:
print("Cannot divide by zero!")
except ValueError:
print("Please enter a valid number!")
except:
print("Some other error occurred")
try-except-finally
try:
file = open("[Link]", "r")
print([Link]())
except FileNotFoundError:
print("File not found!")
finally:
print("Program finished.") # always runs, error or not
Note: 'finally' always runs — use it to close files, database connections, etc.
Page 26
Python Programming Mohanraj R
Iterators
An iterator goes through items one by one. Every for loop uses an iterator internally. Needs two methods:
__iter__() and __next__()
class MyNumbers:
def __iter__(self):
self.n = 1
return self
def __next__(self):
if self.n <= 5:
x = self.n
self.n += 1
return x
else:
raise StopIteration # stops the iterator
obj = MyNumbers()
for i in obj:
print(i) # Output: 1 2 3 4 5
Generators
A generator is an easy way to create an iterator using yield. yield pauses the function and remembers where it
stopped.
def my_gen():
yield 1
yield 2
yield 3
for i in my_gen():
print(i) # Output: 1 2 3
Decorators
A decorator adds extra functionality to a function without changing the original function.
def wish(func):
def wrapper():
print("Good morning!")
func()
print("Have a nice day!")
return wrapper
Page 27
Python Programming Mohanraj R
@wish
def student():
print("I am a student.")
student()
# Output:
# Good morning!
# I am a student.
# Have a nice day!
Page 28
Python Programming Mohanraj R
Logging
Logging records what happens in your program. It is better than print() for real projects.
Level When to Use
DEBUG Detailed info for diagnosing problems
INFO Confirm things are working as expected
WARNING Something unexpected but not an error
ERROR A serious problem occurred
CRITICAL A very serious error — program may crash
import logging
[Link](level=[Link])
balance = 1000
[Link]("User logged in")
withdraw = 200
if withdraw > balance:
[Link]("Insufficient balance")
else:
balance -= withdraw
[Link](f"Transaction successful. New balance: {balance}")
Collections Module
The collections module gives special data structures more useful than normal list/dict.
Page 29
Python Programming Mohanraj R
Page 30
Python Programming Mohanraj R
Step-by-Step Instructions
1. Get two numbers from the user using input() and convert to float
2. Ask the user to choose an operation (+, -, *, /)
3. Use if-elif-else to perform the selected operation
4. Handle division by zero: if b == 0 print an error message
5. Display the result clearly
6. Bonus: Wrap in a while loop so the user can calculate multiple times
Step-by-Step Instructions
7. Import the random module
8. Generate a random number between 1 and 100 using [Link]()
9. Use a while loop to keep asking the user for a guess
10. Tell the user if their guess is Too High, Too Low, or Correct
11. Count and display how many attempts the user took
12. Bonus: Limit attempts to 10 and end the game if exceeded
Step-by-Step Instructions
13. Create a function to collect marks for 5 subjects using a loop
14. Calculate total using sum() and average using total / 5
15. Use if-elif-else to assign a grade: A (90+), B (75+), C (50+), D (35+), Fail
16. Store student details in a dictionary
17. Display the full report card: name, marks, total, average, grade
18. Bonus: Store multiple students in a list of dictionaries
Page 31
Python Programming Mohanraj R
Step-by-Step Instructions
19. Create an empty list to store tasks
20. Show a menu: 1-Add Task 2-View Tasks 3-Delete Task 4-Quit
21. Use a while loop to keep showing the menu
22. Implement add, view, and delete as separate functions
23. Save tasks to a text file so they persist between program runs
24. Bonus: Add a 'Mark as Complete' feature
Step-by-Step Instructions
25. Use a dictionary to store contacts (name as key, phone as value)
26. Create functions: add_contact(), view_contacts(), search_contact(), delete_contact()
27. Use a while loop with a menu to navigate between features
28. Handle 'contact not found' using try-except or if-else
29. Save contacts to a file and load them when the program starts
30. Bonus: Add email and address using nested dictionaries
Page 32