The Ultimate Python Handbook
The Ultimate Python Handbook
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!
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.
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] .
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.
Code Example:
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.
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:
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")
4. print("Item\tPrice")
print("Apples\t50")
Topic 5: Variables
Theory:
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.
Code Example:
The Ultimate Python Handbook: Definitive Student Edition (By Aditya Patil) 6
print("The score is:", player_score)
Topic 6: Datatypes
Theory:
Float ( float ): Used for numbers with a decimal point (e.g., 99.50, 3.14).
Code Example:
The Ultimate Python Handbook: Definitive Student Edition (By Aditya Patil) 7
1. Create a variable book_title (string) and release_year (integer).
Solutions
1. book_title = "The Alchemist"
release_year = 1988
2. book_price = 250.75
3. is_available = True
The main functions for this are int() , float() , and str() .
The Ultimate Python Handbook: Definitive Student Edition (By Aditya Patil) 8
Code Example:
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.
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.
If you need to perform math with the user's input, you MUST convert it to
an int or float using type casting.
Code Example:
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!")
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.
3. A person can watch a movie if they have a ticket or they are a staff member.
Write a program to check this.
Solutions
1. number = int(input("Enter a number: "))
if number % 2 != 0: print("The number is odd.")
else: print("The number is even.")
3. has_ticket = True
is_staff = False
can_watch = has_ticket or is_staff
print("Can the person watch the movie?", can_watch)
The Ultimate Python Handbook: Definitive Student Edition (By Aditya Patil) 12
Theory:
if : The simplest form. The code block runs only if the condition is True .
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.
Code Example:
score = 85
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."
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.")
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.
continue : Skips the rest of the current iteration and moves to the next one.
Code Example:
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 ).
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
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:
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:
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:
Dictionaries
Theory: An unordered, changeable collection of key:value pairs. Each key must
be unique.
Code Example:
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}
They help in organizing code and avoiding repetition (DRY: Don't Repeat
Yourself).
Code Example:
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")
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 Ultimate Python Handbook: Definitive Student Edition (By Aditya Patil) 19
Modes: 'w' (write - overwrites file), 'a' (append - adds to end of file), 'r'
Code Example:
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)
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."
2. Inheritance
Theory:
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.
Code Example:
3. Encapsulation
Theory:
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
account = BankAccount(1000)
# print(account.__balance) # This will cause an AttributeError
print(f"Current balance is ${account.get_balance()}")
4. Polymorphism
Theory:
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.
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())
5. Abstraction
Theory:
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).
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:
my_square = Square(4)
The Ultimate Python Handbook: Definitive Student Edition (By Aditya Patil) 26
print("Area of square:", my_square.area())
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.
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
The Ultimate Python Handbook: Definitive Student Edition (By Aditya Patil) 27
# Call the overridden display method
[Link]()
The Ultimate Python Handbook: Definitive Student Edition (By Aditya Patil) 28