0% found this document useful (0 votes)
4 views28 pages

The Ultimate Python Handbook

The Ultimate Python Handbook: Definitive Student Edition by Aditya Patil serves as an introductory guide for beginners to learn Python programming. It covers fundamental concepts such as programming theory, Python setup, variables, data types, user input, operators, and conditional statements, providing practical examples and exercises. The handbook aims to equip readers with the skills to create programs and understand programming logic effectively.

Uploaded by

ramlal001729
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views28 pages

The Ultimate Python Handbook

The Ultimate Python Handbook: Definitive Student Edition by Aditya Patil serves as an introductory guide for beginners to learn Python programming. It covers fundamental concepts such as programming theory, Python setup, variables, data types, user input, operators, and conditional statements, providing practical examples and exercises. The handbook aims to equip readers with the skills to create programs and understand programming logic effectively.

Uploaded by

ramlal001729
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

The Ultimate Python

Handbook: Definitive Student


Edition (By Aditya Patil)

The Ultimate Python Handbook: Definitive Student Edition (By Aditya Patil) 1
The Ultimate Python Handbook: Definitive Student Edition (By Aditya Patil) 2
Welcome, future coder! Get ready to start an exciting
adventure into the world of Python. This isn't just a
handbook; it's your personal guide to becoming a
programming wizard. We'll learn and we'll build
amazing things together. Let's begin!

Topic 1: Introduction to Programming


Theory:

Programming is simply the act of giving step-by-step instructions to a


computer to perform a specific task.

Computers don't understand human languages like English or Hindi; they


understand special languages called programming languages.

Python is one of the most popular and beginner-friendly programming


languages.

You can use programming to create websites, build games, analyze data,
and even control robots.

Real-Life Analogy: Imagine you are teaching your friend a new recipe. You
have to give them clear, sequential steps (like "1. Chop the onions, 2. Heat
the pan, 3. Add oil"). Programming is just like writing that recipe for a
computer.

Topic 2: Introduction to Python & Setup


Theory:

Python is a high-level language, which means its syntax (grammar) is easy


for humans to read and write, much like English.

It is a "general-purpose" language, meaning it's a versatile tool you can


use to build almost anything.

The Ultimate Python Handbook: Definitive Student Edition (By Aditya Patil) 3
To start writing Python code, you need to install the Python "interpreter"
on your computer, which acts as a translator between your code and the
computer's hardware.

The best place to get Python is from its official website: [Link] .

Real-Life Analogy: Installing Python is like buying a dictionary for a new


language. Before you can start writing or understanding the language, you
need the tool (the dictionary/interpreter) that can make sense of the
words. During installation, checking "Add to PATH" is like putting that
dictionary on your main desk so you can access it easily from anywhere.

Topic 3: Our First Python Program


Theory:

The first program you write in any new language is traditionally the "Hello,
World!" program.

Its purpose is simple: to make sure your setup is working correctly and to
give you your first taste of success.

In Python, we use the built-in print() function to display any text or value on
the screen.

Whatever you want to print as text should be enclosed in double ( " ) or


single ( ' ) quotes.

Code Example:

# The print() function is used to display output on the screen.


print("Hello, World!")

Topic 4: Comments, Escape Sequences, and print()


Theory:

Comments: These are notes in your code that Python ignores. They start
with a hash symbol ( # ) and are used to explain what your code does.

The Ultimate Python Handbook: Definitive Student Edition (By Aditya Patil) 4
print() : This is a function that displays output. You can give it text,
numbers, or variables to print.

Escape Sequences: These are special character combinations inside a


string that have a specific meaning.

\n (New Line): Moves the output to the next line.

\t (Tab): Adds a horizontal space, useful for alignment.

Real-Life Analogy: Comments are like sticky notes you put in a book to
remind yourself of something important. Escape sequences are like secret
codes in your text; \n is a secret code for "press the Enter key".

Code Example:

# This is a comment, used for explaining the code.


print("This line will be printed.")

# Using \n to print on two separate lines


print("Line 1\nLine 2")

# Using \t to add a tab space for neat columns


print("Name:\tAge:")
print("John\t30")

Practice Questions
1. Write a program to print your full name.

2. Print your address on three separate lines using only one print() statement.

3. Write a program that prints a number, and add a comment above it explaining
that it's your lucky number.

4. Print the headers "Item" and "Price" separated by a tab. On the next line, print
"Apples" and "50" also separated by a tab.

Solutions

The Ultimate Python Handbook: Definitive Student Edition (By Aditya Patil) 5
1. print("Your Full Name")

2. print("123, ABC Street\nNew Delhi\nIndia")

3. # This is my lucky number


print(7)

4. print("Item\tPrice")
print("Apples\t50")

Topic 5: Variables
Theory:

A variable is a container used to store a piece of data.

You give the container a name (the variable name) and put a value inside it
using the equals sign ( = ).

This allows you to label and store information, so you can use it later in
your program just by calling its name.

You can also change the value inside a variable at any time.

Real-Life Analogy: Think of a variable as a labeled box. You can have a


box labeled my_age and put the number 25 inside it. Later, if you have a
birthday, you can replace the 25 with 26 . The label on the box stays the
same.

Code Example:

# Assigning the value "Virat" to a variable named player_name


player_name = "Virat"
print("The player's name is:", player_name)

# The value of the variable can be changed


player_name = "Rohit"
print("Now, the player's name is:", player_name)

# A variable can also store numbers


player_score = 100

The Ultimate Python Handbook: Definitive Student Edition (By Aditya Patil) 6
print("The score is:", player_score)

Topic 6: Datatypes
Theory:

A datatype specifies the type of value a variable holds. Python needs to


know this to perform operations correctly.

String ( str ): Used for text. Anything in quotes.

Integer ( int ): Used for whole numbers (e.g., 10, -50).

Float ( float ): Used for numbers with a decimal point (e.g., 99.50, 3.14).

Boolean ( bool ): Represents one of two values: True or False .

Real-Life Analogy: Think of different sections in your wallet. You have a


section for paper money ( int or float ), a section for your ID card ( str ), and
maybe a slot that holds a "yes/no" token for a decision ( bool ). Each section
is designed for a specific type of item.

Code Example:

# Variables of different datatypes


city_name = "Mumbai" # String
pincode = 400001 # Integer
temperature = 28.5 # Float
is_raining = False # Boolean

# The type() function tells you the datatype of a variable


print("Type of city_name is:", type(city_name))
print("Type of pincode is:", type(pincode))
print("Type of temperature is:", type(temperature))
print("Type of is_raining is:", type(is_raining))

Practice Questions (for Variables & Datatypes)

The Ultimate Python Handbook: Definitive Student Edition (By Aditya Patil) 7
1. Create a variable book_title (string) and release_year (integer).

2. Create a variable book_price (float).

3. Create a boolean variable is_available and set it to True .

4. Print the type of each variable you created.

Solutions
1. book_title = "The Alchemist"
release_year = 1988

2. book_price = 250.75

3. is_available = True

4. book_title = "The Alchemist"


release_year = 1988
book_price = 250.75
is_available = True
print(type(book_title))
print(type(release_year))
print(type(book_price))
print(type(is_available))

Topic 7: Type Casting


Theory:

Type casting is the process of converting a variable from one datatype to


another.

This is crucial when you need to perform operations between different


types, like doing math with a number that was initially stored as text.

The main functions for this are int() , float() , and str() .

You can convert a string of digits to an integer, an integer to a float, or a


number to a string, but you can't convert a word like "hello" into a number.

Real-Life Analogy: Imagine you have a phone number written on a sticky


note ( string ). You can't dial the sticky note. You first have to read the digits
and punch them into your phone's keypad (converting it to a numerical
format your phone understands). This conversion is type casting.

The Ultimate Python Handbook: Definitive Student Edition (By Aditya Patil) 8
Code Example:

# String to Integer for calculations


score_from_user = "100"
score_as_int = int(score_from_user)
print("Bonus score:", score_as_int + 20)

# Integer to String for joining with text (concatenation)


age = 25
print("The user's age is " + str(age)) # Cannot join string with integer direc
tly

Practice Questions
1. You have a variable a = "50" . Convert it to an integer, add 10 to it, and print the
result.

2. You have a variable b = 123 . Convert it to a string and print "Roll Number: "
followed by the variable.

3. A variable c = "99.5" is a string. Convert it to a float and print its type.

4. A variable d = 50.0 is a float. Convert it to an integer and print the result.

Solutions
1. a = "50"
result = int(a) + 10
print(result)

2. b = 123
print("Roll Number: " + str(b))

3. c = "99.5"
c_float = float(c)
print(type(c_float))

4. d = 50.0
d_int = int(d)
print(d_int)

The Ultimate Python Handbook: Definitive Student Edition (By Aditya Patil) 9
Topic 8: Taking Input from User
Theory:

The input() function is your way of having a conversation with the user.

It displays a message (a prompt) on the screen and waits for the user to
type something and press Enter.

Crucial Point: input() always returns the data as a string .

If you need to perform math with the user's input, you MUST convert it to
an int or float using type casting.

Real-Life Analogy: Using input() is like asking a question in a survey form.


The user writes their answer in a blank space. That written answer is
initially just text ( string ), even if they write a number. You have to interpret
that text as a number ( int or float ) to do any calculations with it.

Code Example:

# Ask the user for their name (which is a string)


user_name = input("What is your name? ")
print("Hello, " + user_name + "!")

# Ask for age and convert it to an integer for calculations


age_string = input("What is your age? ")
age_int = int(age_string) # Convert string to integer
print("Next year, you will be", age_int + 1, "years old.")

Practice Questions
1. Ask the user for their city name and print it back in a sentence.

2. Ask the user for two numbers, convert them to int , and print their sum.

3. Ask the user for the side of a square and calculate its area (side * side).

4. Ask the user for their first name and last name in two separate inputs, then
print their full name.

The Ultimate Python Handbook: Definitive Student Edition (By Aditya Patil) 10
Solutions
1. city = input("Which city do you live in? ")
print("Wow,", city, "is a beautiful city!")

2. num1 = int(input("Enter the first number: "))


num2 = int(input("Enter the second number: "))
print("Their sum is:", num1 + num2)

3. side = int(input("Enter the side of the square: "))


area = side * side
print("The area of the square is:", area)

4. first_name = input("Enter your first name: ")


last_name = input("Enter your last name: ")
print("Your full name is:", first_name + " " + last_name)

Topic 9: Operators in Python


Theory:

Operators are special symbols that perform operations on values


(operands).

Arithmetic Operators: For math. + ,,, / , % (remainder), * (power of).

Comparison Operators: For comparing values. They always result in a


True or False . == (is equal to), != (is not equal to), > , < .

Logical Operators: For combining boolean values. and (both must be


true), or (at least one must be true), not (inverts the boolean).

Real-Life Analogy: Think of operators as verbs or action words. The


numbers/variables are the nouns. In "5 + 3", the + operator is the action
of "adding". In "age > 18", the > operator is the action of "comparing".

Code Example:

# Arithmetic
a = 10
b=3
print("Remainder of 10/3:", a % b) # Output: 1
print("2 to the power 3:", 2 ** 3) # Output: 8

The Ultimate Python Handbook: Definitive Student Edition (By Aditya Patil) 11
# Comparison
age = 18
print("Is age equal to 18?", age == 18) # Output: True

# Logical
has_license = True
has_helmet = False
print("Can ride bike safely?", has_license and has_helmet) # Output: False

Practice Questions
1. Write a program to check if a number entered by the user is odd.

2. Check if a user's age is 18 or older.

3. A person can watch a movie if they have a ticket or they are a staff member.
Write a program to check this.

4. Calculate 10 divided by 3 using both / and // . Observe the difference.

Solutions
1. number = int(input("Enter a number: "))
if number % 2 != 0: print("The number is odd.")
else: print("The number is even.")

2. age = int(input("Enter your age: "))


is_adult = age >= 18
print("Is the user an adult?", is_adult)

3. has_ticket = True
is_staff = False
can_watch = has_ticket or is_staff
print("Can the person watch the movie?", can_watch)

4. result1 = 10 / 3 # Normal division


result2 = 10 // 3 # Floor division
print("10 / 3 is:", result1) # Output: 3.333...
print("10 // 3 is:", result2) # Output: 3

Topic 10: Conditional Statements (The Decision


Maker)

The Ultimate Python Handbook: Definitive Student Edition (By Aditya Patil) 12
Theory:

Conditional statements allow your program to execute different blocks of


code based on whether a condition is true or false. This is how programs
make decisions.

if : The simplest form. The code block runs only if the condition is True .

if-else : Provides an alternative path. If the if condition is False , the else

block runs.

if-elif-else : The "Choose Your Own Adventure" structure. It lets you check
multiple conditions in order. elif is short for "else if". As soon as one
condition is met, its block runs, and the rest are skipped.

Real-Life Analogy: Imagine you're deciding what to wear. "If it is raining, I


will take a raincoat. Else if it is sunny, I will wear a t-shirt. Else (if it's just
cloudy), I will wear a jacket." Your program follows this exact logic to make
decisions.

Code Example:

score = 85

if score >= 90:


print("Grade: A")
elif score >= 80:
print("Grade: B") # This block will run
elif score >= 70:
print("Grade: C")
else:
print("Grade: F")

Explanation: Python checks the conditions from top to bottom. Since 85 >= 90
is false, it checks the next one. 85 >= 80 is true, so it prints "Grade: B" and
skips the rest of the chain.

Practice Questions

The Ultimate Python Handbook: Definitive Student Edition (By Aditya Patil) 13
1. Ask the user to enter a number. Print whether the number is positive, negative,
or zero.

2. Create a simple login system. If the username is "admin" and the password is
"python123", print "Access Granted", otherwise print "Access Denied".

3. Ask a user for their age. If they are younger than 13, print "You are a child." If
they are between 13 and 19 (inclusive), print "You are a teenager." Otherwise,
print "You are an adult."

4. Ask for a number and check if it's divisible by 5.

Solutions
1. num = int(input("Enter a number: "))
if num > 0: print("The number is positive.")
elif num < 0: print("The number is negative.")
else: print("The number is zero.")

2. username = input("Enter username: ")


password = input("Enter password: ")
if username == "admin" and password == "python123": print("Access Granted.")
else: print("Access Denied.")

3. age = int(input("Enter your age: "))


if age < 13: print("You are a child.")
elif age >= 13 and age <= 19: print("You are a teenager.")
else: print("You are an adult.")

4. num = int(input("Enter a number: "))


if num % 5 == 0: print("The number is divisible by 5.")
else: print("The number is not divisible by 5.")

Topic 11: Loops (The Repeater)


Theory:

Loops are used to execute a block of code repeatedly, saving you from
writing the same code over and over.

forLoop: Used when you want to iterate over a sequence (like a list, a
string, or a range of numbers). You use it when you know how many times
you want the loop to run.

The Ultimate Python Handbook: Definitive Student Edition (By Aditya Patil) 14
while Loop: Repeats a block of code as long as a certain condition remains
True . You use it when you don't know the exact number of iterations.

break : Immediately exits the current loop.

continue : Skips the rest of the current iteration and moves to the next one.

Real-Life Analogy: A for loop is like a factory worker on an assembly line


who has to process exactly 100 items. A while loop is like a security guard
who has to keep checking a door while it's unlocked; the loop stops as
soon as the door is locked.

Code Example:

# for loop with range to print numbers 1 to 5


print("For loop from 1 to 5:")
for i in range(1, 6): # range(1, 6) gives numbers 1, 2, 3, 4, 5
print(i)

# while loop to do the same thing


print("\nWhile loop from 1 to 5:")
count = 1
while count <= 5:
print(count)
count += 1 # Important: update the counter to avoid an infinite loop!

Practice Questions
1. Use a for loop to print the multiplication table of 7 (from 7x1 to 7x10).

2. Write a program that prints all numbers from 1 to 20, but skips numbers
divisible by 3 (use continue ).

3. Use a while loop to print all even numbers from 2 to 20.

4. Create a list of your favorite fruits. Use a for loop to print each fruit.

Solutions
1. for i in range(1, 11): print(f"7 x {i} = {7 * i}")

The Ultimate Python Handbook: Definitive Student Edition (By Aditya Patil) 15
2. for i in range(1, 21): if i % 3 == 0: continue # Skip this number print(i)

3. num = 2
while num <= 20: print(num) num += 2

4. fruits = ["Apple", "Banana", "Mango", "Grapes"]


for fruit in fruits: print(fruit)

Topic 12 - 16: Data Structures


Data structures are specialized formats for organizing, processing, retrieving, and
storing data.

Strings
Theory: A sequence of characters. They are immutable (cannot be changed
after creation). You can access parts of a string using slicing [start:end] and use
various built-in methods to manipulate them.

Code Example:

my_string = "Hello, Python!"


print("Substring:", my_string[7:13]) # Slicing
print("Uppercase:", my_string.upper()) # Method

Lists
Theory: An ordered and changeable (mutable) collection of items. They can
hold items of different data types.

Analogy: A shopping list on a piece of paper. You can add items, cross
them off, or change them.

Code Example:

fruits = ["apple", "banana", "cherry"]


fruits[1] = "blueberry" # Change an item
[Link]("orange") # Add an item to the end

The Ultimate Python Handbook: Definitive Student Edition (By Aditya Patil) 16
print("Updated list:", fruits)

Tuples
Theory: An ordered and unchangeable (immutable) collection of items. They
are faster than lists and protect your data from accidental changes.

Analogy: The list of months in a year. It's ordered and never changes.

Code Example:

coordinates = (10.0, 20.0, "North")


print("Latitude:", coordinates[0])
# coordinates[0] = 5.0 # This would cause a TypeError

Dictionaries
Theory: An unordered, changeable collection of key:value pairs. Each key must
be unique.

Analogy: A real dictionary or a phone book. You look up a unique word


(the key ) to find its definition (the value ).

Code Example:

student = {"name": "John Doe", "age": 21}


print("Student's name:", student["name"])
student["age"] = 22 # Update a value
print("Updated age:", student["age"])

Sets
Theory: An unordered collection of unique items. Duplicates are automatically
removed.

The Ultimate Python Handbook: Definitive Student Edition (By Aditya Patil) 17
Analogy: A bag of unique marbles. If you try to add a marble that's
already in the bag, it doesn't change anything.

Code Example:

numbers = {1, 2, 3, 4, 4, 5, 2}
print("Unique numbers set:", numbers) # Output: {1, 2, 3, 4, 5}

Topic 17: Functions


Theory:

A function is a block of reusable code that performs a specific action.

They help in organizing code and avoiding repetition (DRY: Don't Repeat
Yourself).

You define a function using the def keyword.

You can pass data into functions as parameters (or arguments).

Functions can optionally return a value back to the caller.

Analogy: A coffee machine is a function. You call it by pressing a button.


You give it parameters (water, coffee powder). It performs a process and
returns a value (a cup of coffee).

Code Example:

# Defining a function that takes parameters and returns a value


def calculate_area(length, width):
"""This function calculates the area of a rectangle."""
area = length * width
return area

# Calling the function and storing the result


room_area = calculate_area(12, 10)

The Ultimate Python Handbook: Definitive Student Edition (By Aditya Patil) 18
print(f"The area of the room is: {room_area} sq ft.")

Practice Questions
1. Write a function greet(name) that takes a name as a parameter and prints a
greeting.

2. Write a function that calculates the area of a circle ( area = 3.14 * r * r ). It should
take the radius r as a parameter and return the area.

3. Write a function find_max(numbers) that takes a list of numbers and returns the
largest number.

4. Write a function is_even(number) that returns True if a number is even, and False

otherwise.

Solutions
1. def greet(name): print(f"Hello, {name}! Have a great day.")
greet("Alice")

2. def calculate_circle_area(radius): return 3.14 * radius * radius


area = calculate_circle_area(5)
print(area)

3. def find_max(numbers): return max(numbers)


print(find_max([10, 50, 2, 99, 45]))

4. def is_even(number): return number % 2 == 0


print(is_even(10)) # True
print(is_even(7)) # False

Topic 18: File Handling


Theory:

File handling allows your program to read from and write to files on your
computer, making data persistent (it stays even after the program closes).

The with open(...) syntax is recommended as it handles closing the file


automatically.

The Ultimate Python Handbook: Definitive Student Edition (By Aditya Patil) 19
Modes: 'w' (write - overwrites file), 'a' (append - adds to end of file), 'r'

(read - reads file).

Real-Life Analogy: Think of it as a diary. 'w' is like opening a new blank


page, erasing anything that was there before. 'a' is like finding the last
written line and adding new text after it. 'r' is just reading what's already
on the page.

Code Example:

# 1. Writing to a file (mode 'w')


with open("my_diary.txt", "w") as file:
[Link]("Today I learned about file handling.\n")

# 2. Appending to the file (mode 'a')


with open("my_diary.txt", "a") as file:
[Link]("It was fun!\n")

# 3. Reading from the file (mode 'r')


with open("my_diary.txt", "r") as file:
content = [Link]()
print(content)

Practice Questions
1. Write a program that asks the user for their name and saves it to a file named
[Link] .

2. Write a program that reads the content of [Link] and prints it to the console.

3. Ask the user for their favorite color and append it to a file called [Link] .

4. Run the program from Q3 multiple times with different colors. Then, write a
program to read and print all the colors from [Link] .

Solutions
1. name = input("Enter your name: ")
with open("[Link]", "w") as file: [Link](name)

The Ultimate Python Handbook: Definitive Student Edition (By Aditya Patil) 20
print("Name saved successfully.")

2. with open("[Link]", "r") as file: content = [Link]() print("Name stored in file is:", content)

3. color = input("What is your favorite color? ")


with open("[Link]", "a") as file: [Link](color + "\n")
print("Color appended.")

4. with open("[Link]", "r") as file: all_colors = [Link]() print(all_colors)

Topic 19: Object-Oriented Programming (OOP)


Theory:
OOP is a way of structuring programs around "objects" which contain both
data (attributes) and behaviors (methods). This makes code more organized,
reusable, and easier to manage, especially for large projects. The four main
pillars of OOP are:

1. Encapsulation: Bundling data and methods together, and restricting


access.

2. Inheritance: Creating new classes based on existing ones.

3. Polymorphism: Allowing objects of different classes to be treated as


objects of a common super class.

4. Abstraction: Hiding complex implementation details and showing only the


necessary features.

1. Classes and Objects


Theory:

A Class is a blueprint or template for creating objects.

An Object is an actual instance created from that blueprint.

The __init__() method is a special method called a constructor, which runs


automatically whenever a new object is created from the class.

self is a special parameter that refers to the object instance itself, allowing
it to access its own attributes and methods.

The Ultimate Python Handbook: Definitive Student Edition (By Aditya Patil) 21
Real-Life Analogy: A car manufacturing company has a blueprint for a
"Sedan" (the Class ). Every individual car that comes off the assembly line
based on that blueprint is an Object . Each car has its own color and
engine_number (attributes), but they all share the same basic design and can

start_engine() (method).

Code Example:

class Car:
# The constructor method
def __init__(self, color, model):
# These are attributes
[Link] = color
[Link] = model

# This is a method
def start_engine(self):
return f"The {[Link]} {[Link]}'s engine is running."

# Creating objects (instances) from the Car class


my_car = Car("Blue", "Sedan")
your_car = Car("Red", "SUV")

# Accessing attributes and calling methods


print(my_car.color) # Blue
print(your_car.start_engine()) # The Red SUV's engine is running.

2. Inheritance
Theory:

Inheritance allows a new class (child class) to inherit attributes and


methods from an existing class (parent class).

This promotes code reuse ("Don't Repeat Yourself" - DRY principle).

The Ultimate Python Handbook: Definitive Student Edition (By Aditya Patil) 22
The child class can use all the features of the parent class and can also
add its own new features or override existing ones.

Real-Life Analogy: Think of "Vehicles". A "Car" is a "Vehicle". A "Bicycle"


is a "Vehicle". Both Car and Bicycle inherit common properties from
Vehicle (like having wheels and a brand), but they also have their own
unique features (a car has an engine, a bicycle has pedals).

Code Example:

class Vehicle: # Parent Class


def __init__(self, brand):
[Link] = brand
def move(self):
return "Moving forward"

class Car(Vehicle): # Child Class inheriting from Vehicle


def __init__(self, brand, model):
# Call the parent's constructor to set the brand
super().__init__(brand)
[Link] = model # Add a new attribute

my_car = Car("Honda", "Civic")


print(my_car.brand) # Inherited attribute
print(my_car.model) # Own attribute
print(my_car.move()) # Inherited method

3. Encapsulation
Theory:

Encapsulation is the bundling of data (attributes) and the methods that


operate on that data into a single unit (a class).

It also involves restricting direct access to an object's data (data hiding) to


prevent accidental modification.

The Ultimate Python Handbook: Definitive Student Edition (By Aditya Patil) 23
In Python, we use a double underscore __ prefix to make an attribute
"private". This means it cannot be easily accessed from outside the class.

Real-Life Analogy: A car's dashboard. You can use the steering wheel and
pedals ( public methods ) to control the car, but you are prevented from directly
touching the complex engine wiring ( private data ). This protects the engine
from being damaged accidentally.

Code Example:

class BankAccount:
def __init__(self, initial_balance):
self.__balance = initial_balance # Private attribute

def deposit(self, amount):


if amount > 0:
self.__balance += amount
print("Deposit successful.")
else:
print("Invalid deposit amount.")

# A "getter" method to safely access the balance


def get_balance(self):
return self.__balance

account = BankAccount(1000)
# print(account.__balance) # This will cause an AttributeError
print(f"Current balance is ${account.get_balance()}")

4. Polymorphism
Theory:

Polymorphism (meaning "many forms") is the ability of different objects to


respond to the same method call in their own unique ways.

The Ultimate Python Handbook: Definitive Student Edition (By Aditya Patil) 24
It allows you to write code that can work with objects of different classes,
as long as they share a common method name.

This makes your code more flexible and adaptable.

Real-Life Analogy: A USB port. You can plug in a mouse, a keyboard, or a


flash drive (different objects ). The computer knows how to handle each one
through the same port (the function call ), and each device responds
differently to the computer's signals.

Code Example:

class Cat:
def speak(self): return "Meow"
class Dog:
def speak(self): return "Woof"
class Duck:
def speak(self): return "Quack"

# This function works with any object that has a .speak() method
def make_animal_speak(animal_object):
print(animal_object.speak())

make_animal_speak(Cat()) # Outputs: Meow


make_animal_speak(Dog()) # Outputs: Woof
make_animal_speak(Duck()) # Outputs: Quack

5. Abstraction
Theory:

Abstraction means hiding the complex implementation details and showing


only the essential features of the object.

It helps in reducing complexity and focusing on what the object does, not
how it does it.

The Ultimate Python Handbook: Definitive Student Edition (By Aditya Patil) 25
An abstract class is a template that cannot be instantiated on its own but
forces its child classes to implement certain methods (called abstract
methods).

Real-Life Analogy: A TV remote. You press the "power" button ( abstract


method ). You don't know or need to know the complex circuitry that makes

it work ( implementation ). You just know that any remote for a TV must have a
power button. The abstract class is like a design specification that says "all
child classes must have this feature".

Code Example:

from abc import ABC, abstractmethod

class Shape(ABC): # This is an Abstract Class


@abstractmethod
def area(self): # This is an Abstract Method
pass

class Square(Shape): # Child class must implement area()


def __init__(self, side):
[Link] = side
def area(self):
return [Link] * [Link]

class Circle(Shape): # Child class must implement area()


def __init__(self, radius):
[Link] = radius
def area(self):
return 3.14 * [Link] * [Link]

# you cannot create an object of an abstract class


# shape = Shape() # This would cause an error

my_square = Square(4)

The Ultimate Python Handbook: Definitive Student Edition (By Aditya Patil) 26
print("Area of square:", my_square.area())

Practice Questions (for OOP)


1. Create a Person class with name and age attributes.

2. Create a Student class that inherits from Person and has an additional student_id

attribute.

3. Add a display() method to the Person class that prints the name and age.

4. Override the display() method in the Student class to also print the student ID.

5. Create a Student object and call its display() method.

Solutions

class Person:
def __init__(self, name, age):
[Link] = name
[Link] = age

def display(self):
print(f"Name: {[Link]}, Age: {[Link]}")

class Student(Person):
def __init__(self, name, age, student_id):
super().__init__(name, age) # Call parent constructor
self.student_id = student_id

def display(self): # Override parent's method


super().display() # Call parent's display method first
print(f"Student ID: {self.student_id}")

# Create a student object


student1 = Student("Rohan", 20, "S12345")

The Ultimate Python Handbook: Definitive Student Edition (By Aditya Patil) 27
# Call the overridden display method
[Link]()

Summary and Conclusion


Congratulations on making it to the end! This handbook has given you a strong
foundation in Python's core concepts, from the very basics to the powerful
paradigm of Object-Oriented Programming. The key to becoming a great
programmer is practice. Keep building small projects, solve problems, and never
stop learning.
Happy Coding!

The Ultimate Python Handbook: Definitive Student Edition (By Aditya Patil) 28

You might also like