The Ultimate Python Handbook
The Ultimate Python Handbook
Welcome to the “Ultimate Python Programming Handbook," your comprehensive guide to PREFACE ........................................................................................................................................... 1
mastering Python programming. This handbook is designed for beginners and anyone looking to Purpose and Audience .................................................................................................................... 1
strengthen their foundational knowledge of Python, a versatile and user-friendly programming Structure and Content ..................................................................................................................... 1
language.
Why Python?................................................................................................................................... 1
1 2
List methods. ................................................................................................................................ 17 Recursion ..................................................................................................................................... 31
Tuples in Python ........................................................................................................................... 17 Chapter 8 – Practice Set .................................................................................................................... 33
Tuple Methods .............................................................................................................................. 17 Project 1: Snake, Water, Gun Game ................................................................................................... 34
Chapter 4 - Practice Set .................................................................................................................... 19 Chapter 9 – File I/O ........................................................................................................................... 35
Chapter 5 – Dictionary & Sets ............................................................................................................ 20 Type of Files. ................................................................................................................................. 35
Properties of Python Dictionaries ................................................................................................... 20 Opening a File ............................................................................................................................... 35
Dictionary Methods ....................................................................................................................... 20 Reading a File in Python ................................................................................................................. 35
Sets in Python. .............................................................................................................................. 20 Other methods to read the file. ...................................................................................................... 36
Properties of Sets .......................................................................................................................... 21 Modes of opening a file .................................................................................................................. 36
Operations on sets ........................................................................................................................ 21 Write Files in Python ...................................................................................................................... 36
Chapter 5 – Practice Set .................................................................................................................... 22 With Statement ............................................................................................................................. 36
Chapter 6 – Conditional Expression ................................................................................................... 23 Chapter 9 – Practice Set .................................................................................................................... 37
If Else and Elif in Python ................................................................................................................. 23 Chapter 10 - Object Oriented Programming ....................................................................................... 38
Code example. ............................................................................................................................. 23 Class............................................................................................................................................ 38
Relational Operators ..................................................................................................................... 24 Object .......................................................................................................................................... 38
Logical Operators ......................................................................................................................... 24 Modelling a problem in OOPs......................................................................................................... 38
Elif clause ..................................................................................................................................... 24 Class Attributes ............................................................................................................................ 38
Important notes: ........................................................................................................................... 24 Instance attributes ........................................................................................................................ 39
Chapter 6 – Practice Set .................................................................................................................... 25 self parameter .............................................................................................................................. 39
Chapter 7 – Loops in Python .............................................................................................................. 26 static method ............................................................................................................................... 39
Types of Loops in Python ............................................................................................................... 26 __init__() constructor ..................................................................................................................... 40
While loop .................................................................................................................................... 26 Chapter 10 – Practice Set .................................................................................................................. 41
For loop ........................................................................................................................................ 27 Chapter 11 - Inheritance & more on OOPs .......................................................................................... 42
range() Function in Python ............................................................................................................. 27 Types of Inheritance ...................................................................................................................... 42
An Example Demonstrating range() function. .................................................................................. 27 Single Inheritance ......................................................................................................................... 42
For Loop with Else ......................................................................................................................... 27 Multiple Inheritance ...................................................................................................................... 43
The Break Statement ..................................................................................................................... 27 Multilevel Inheritance .................................................................................................................... 43
The Continue Statement ................................................................................................................ 28 super() method ............................................................................................................................. 43
Pass statement ............................................................................................................................. 28 class method ................................................................................................................................ 44
Chapter 7 – Practice Set .................................................................................................................... 29 @property Decorators ................................................................................................................... 44
Chapter 8 – Functions & Recursions .................................................................................................. 30 @.getters and @.setters ................................................................................................................ 44
Example and syntax of a function ................................................................................................... 30 Operator Overloading in Python ..................................................................................................... 44
Function call................................................................................................................................. 30 Chapter 11- Practice set ................................................................................................................... 46
Function Definition ....................................................................................................................... 30 Project 2 – The Perfect Guess ............................................................................................................ 47
Types of Functions in Python ......................................................................................................... 30 Chapter 12 – Advanced Python 1 ....................................................................................................... 48
Functions with Arguments ............................................................................................................. 30 Newly added features in python ..................................................................................................... 48
Default Parameter Value ............................................................................................................... 31 Walrus Operator ........................................................................................................................... 48
3 4
Types Definitions in Python ............................................................................................................ 48
Advanced Type Hints ..................................................................................................................... 48
PYTHON PROGRAMMING HANDBOOK
Match Case .................................................................................................................................. 49
WHAT IS PROGRAMMING?
Dictionary Merge & Update Operators ............................................................................................ 49
Just like we use Hindi or English to communicate with each other, we use a
Exception handling in Python ......................................................................................................... 50
programming language like Python to communicate with the computer.
Raising Exceptions ........................................................................................................................ 50
try with else clause ....................................................................................................................... 50 Programming is a way to instruct the computer to perform various tasks.
try with finally ............................................................................................................................... 51
WHAT IS PYTHON?
If __name__== ‘__main__’ in python ................................................................................................ 51
The global keyword ....................................................................................................................... 51 Python is a simple and easy to understand language which feels like reading simple
enumerate function in python ........................................................................................................ 51 English. This Pseudo code nature is easy to learn and understandable by beginners.
List comprehensions ..................................................................................................................... 51
FEATURES OF PYTHON
Chapter 12 – Practice set .................................................................................................................. 52
Chapter 13 – Advanced Python 2 ....................................................................................................... 53 • Easy to understand = Less development time
Virtual envirionment ...................................................................................................................... 53 • Free and open source
Installation ................................................................................................................................... 53
• High level language
• Portable: Works on Linux / Windows / Mac.
pip freeze command ..................................................................................................................... 53
• Fun to work with!
Lambda functions ......................................................................................................................... 53
join method (strings) ..................................................................................................................... 54 INSTALLATION
format method (strings) ................................................................................................................. 54
Python can be easily installed from python.org. When you click on the download
Map, Filter & Reduce ..................................................................................................................... 54
button, python can be installed right after you complete the setup by executing the file
Chapter 13 – Practice Set .................................................................................................................. 56
for your platform.
MEGA Project 1: Jarvis ...................................................................................................................... 57
Features ....................................................................................................................................... 57
Workflow ...................................................................................................................................... 57
Libraries Used............................................................................................................................... 58
Mega Project 2: Auto Reply AI Chatbot ............................................................................................... 59
Description ................................................................................................................................... 59
Features ....................................................................................................................................... 59
Workflow ...................................................................................................................................... 59
Libraries Used............................................................................................................................... 60
5 6
CHAPTER 1 – MODULES, COMMENTS & PIP 1. Single Line Comments: To write a single line comment just add a ‘#’ at the start
of the line.
Let’s write our very first python program. Create a file called hello.py and paste the # This is a Single-Line Comment
below code in it.
2. Multiline Comments: To write multi-line comments you can use ‘#’ at each line
print("hello world") # print is a function (more later)
or you can use the multiline string (""" """)
Execute this file (.py file) by typing python hello.py and you will see Hello World printed """This is an amazing
on the screen. example of a Multiline
comment!"""
MODULES
A module is a file containing code written by somebody else (usually) which can be
imported and used in our programs.
PIP
Pip is the package manager for python. You can use pip to install a module on your
system.
TYPES OF MODULES
There are two types of modules in Python.
COMMENTS
Comments are used to write something which the programmer does not want to
execute. This can be used to mark author name, date etc.
TYPES OF COMMENTS
There are two types of comments in python.
7 8
CHAPTER 1 – PRACTICE SET CHAPTER 2 – VARIABLES AND DATATYPE
1. Write a program to print Twinkle twinkle little star poem in python. A variable is the name given to a memory location in a program. For example.
2. Use REPL and print the table of 5 using it.
a= 30 # variables = container to store a value.
3. Install an external module and use it to perform an operation of your interest.
b= "harry" # keywords = reserved words in python
4. Write a python program to print the contents of a directory using the os module. c= 71.22 # identifiers = class/function/variable name
Search online for the function which does that.
5. Label the program written in problem 4 with comments. DATA TYPES
Primarily these are the following data types in Python:
1. Integers
2. Floating point numbers
3. Strings
4. Booleans
5. None
Python is a fantastic language that automatically identifies the type of data for us.
Examples of a few variable names are: harry, one8, seven, _seven etc.
OPERATORS IN PYTHON
Following are some common operators in python:
9 10
TYPE() FUNCTION AND TYPECASTING. CHAPTER 2 – PRACTICE SET
type() function is used to find the data type of a given variable in python. 1. Write a python program to add two numbers.
2. Write a python program to find remainder when a number is divided by z.
a = 31
3. Check the type of variable assigned using input () function.
type(a) # class <int>
4. Use comparison operator to find out whether ‘a’ given variable a is greater than
b = "31" ‘b’ or not. Take a = 34 and b = 80
type (b) # class <str> 5. Write a python program to find an average of two numbers entered by the user.
A number can be converted into a string and vice versa (if possible) 6. Write a python program to calculate the square of a number entered by the user.
There are many functions to convert one data type into another.
INPUT () FUNCTION
This function allows the user to take input from the keyboard as a string.
11 12
CHAPTER 3 – STRINGS SLICING WITH SKIP VALUE
String is a data type in python. We can provide a skip value as a part of our slice like this:
str = 'harry'
Now when operated on this string ‘str’, these functions do the following:
str = "harry"
print(len(str)) # Output: 5
2. String.endswith("rry") – This function_ tells whether the variable string ends with
the string "rry" or not. If string is "harry", it returns true for "rry" since Harry ends
with rry.
The index in a sting starts from 0 to (length -1) in Python. In order to slice a string, we use
the following syntax: str = "harry"
print(str.endswith("rry")) # Output: True
3. string.count("c") – counts the total number of occurrences of any character.
str = "harry"
count = str.count("r")
print(count) # Output: 2
4. the first character of a given string.
str = "harry"
capitalized_string = str.capitalize()
print(capitalized_string) # Output: "Harry"
5. string.find(word) – This function friends a word and returns the index of first
occurrence of that word in the string.
Negative Indices: Negative indices can also be used as shown in the figure above. -1
str = "harry"
corresponds to the (length - 1) index, -2 to (length - 2).
13 14
index = str.find("rr") CHAPTER 3 – PRACTICE SET
print(index) # Output: 2
6. string.replace (old word, new word ) – This function replace the old word with 1. Write a python program to display a user entered name followed by Good
new word in the entire string. Afternoon using input () function.
2. Write a program to fill in a letter template given below with name and date.
str = "harry" letter = '''
replaced_string = str.replace("r", "l") Dear <|Name|>,
print(replaced_string) # Output: "hally" You are selected!
<|Date|>
'''
15 16
CHAPTER 4 – LISTS AND TUPLES a = (1, 7, 2)
• a.count (1): a count (1) will return number of times 1 occurs in a.
Python lists are containers to store a set of values of any data type.
• a.index (1) will return the index of first occurrence of 1 in a.
LIST INDEXING
A list can be indexed just like a string.
l1 = [7,9,"harry"]
l1[0] # 7
l1[1] # 9
l1[70] # error
l1[0:2] # [7,9] #list slicing
LIST METHODS.
Consider the following list:
l1 = [1,8,7,2,21,15]
• l1.sort(): updates the list to [1,2,7,8,15,21]
• l1.reverse(): updates the list to [15,21,2,7,8,1]
• l1.append(8): adds 8 at the end of the list
• l1.insert(3,8): This will add 8 at 3 index
• l1.pop(2): Will delete element at index 2 and return its value.
• l1.remove(21): Will remove 21 from the list.
TUPLES IN PYTHON
A tuple is an immutable data type in python.
a = () # empty tuple
a = (1,) # tuple with only one element needs a comma
a = (1,7,2) # tuple with more than one element
TUPLE METHODS
Consider the following tuple.
17 18
CHAPTER 4 - PRACTICE SET CHAPTER 5 – DICTIONARY & SETS
1. Write a program to store seven fruits in a list entered by the user. Dictionary is a collection of keys-value pairs.
2. Write a program to accept marks of 6 students and display them in a sorted
manner. Syntax:
3. Check that a tuple type cannot be changed in python.
a = {
4. Write a program to sum a list with 4 numbers. "key": "value",
5. Write a program to count the number of zeros in the following tuple: "harry": "code",
a = (7, 0, 8, 0, 0, 9) "marks": "100",
"list": [1, 2, 9]
}
DICTIONARY METHODS
Consider the following dictionary.
a={"name":"harry"
"from":"india"
"marks":[92,98,96]}
• a.items(): Returns a list of (key,value)tuples.
• a.keys(): Returns a list containing dictionary's keys.
• a.update({"friends":}): Updates the dictionary with supplied key-value pairs.
• a.get("name"): Returns the value of the specified keys (and value is returned
eg."harry" is returned here).
SETS IN PYTHON.
Set is a collection of non-repetitive elements.
19 20
If you are a programming beginner without much knowledge of mathematical CHAPTER 5 – PRACTICE SET
operations on sets, you can simply look at sets in python as data types containing
unique values. 1. Write a program to create a dictionary of Hindi words with values as their English
translation. Provide user with an option to look it up!
PROPERTIES OF SETS 2. Write a program to input eight numbers from the user and display all the unique
numbers (once).
1. Sets are unordered => Element’s order doesn’t matter
3. Can we have a set with 18 (int) and '18' (str) as a value in it?
2. Sets are unindexed => Cannot access elements by index
4. What will be the length of following set s:
3. There is no way to change items in sets.
s = set()
4. Sets cannot contain duplicate values. s.add(20)
s.add(20.0)
OPERATIONS ON SETS s.add('20') # length of s after these operations?
5. s = {}
Consider the following set:
What is the type of 's'?
s = {1,8,2,3} 6. Create an empty dictionary. Allow 4 friends to enter their favorite language as
• len(s): Returns 4, the length of the set value and use key as their names. Assume that the names are unique.
• s.remove(8): Updates the set s and removes 8 from s. 7. If the names of 2 friends are same; what will happen to the program in problem
6?
• s.pop(): Removes an arbitrary element from the set and return the element
8. If languages of two friends are same; what will happen to the program in problem
removed.
6?
• s.clear():empties the set s.
9. Can you change the values inside a list which is contained in set S?
• s.union({8,11}): Returns a new set with all items from both sets. {1,8,2,3,11}.
s = {8, 7, 12, "Harry", [1,2]}
• s.intersection({8,11}): Return a set which contains only item in both sets {8}.
21 22
CHAPTER 6 – CONDITIONAL EXPRESSION RELATIONAL OPERATORS
Sometimes we want to play PUBG on our phone if the day is Sunday. Relational Operators are used to evaluate conditions inside the if statements. Some
examples of relational operators are:
Sometimes we order Ice Cream online if the day is sunny.
==: equals.
Sometimes we go hiking if our parents allow.
> =: greater than/ equal to.
All these are decisions which depend on a condition being met.
< =: lesser than/ equal to.
In python programming too, we must be able to execute instructions on a condition(s)
being met. LOGICAL OPERATORS
This is what conditionals are for! In python logical operators operate on conditional statements. For Example:
IF ELSE AND ELIF IN PYTHON • and – true if both operands are true else false.
• or – true if at least one operand is true or else false.
If else and elif statements are a multiway decision taken by our program due to certain
• not – inverts true to false & false to true.
conditions in our code.
23 24
CHAPTER 6 – PRACTICE SET CHAPTER 7 – LOOPS IN PYTHON
1. Write a program to find the greatest of four numbers entered by the user. Sometimes we want to repeat a set of statements in our program. For instance: Print 1
2. Write a program to find out whether a student has passed or failed if it requires a to 1000.
total of 40% and at least 33% in each subject to pass. Assume 3 subjects and
Loops make it easy for a programmer to tell the computer which set of instructions to
take marks as an input from the user.
repeat and how!
3. A spam comment is defined as a text containing following keywords:
“Make a lot of money”, “buy now”, “subscribe this”, “click this”. Write a program
TYPES OF LOOPS IN PYTHON
to detect these spams.
4. Write a program to find whether a given username contains less than 10 Primarily there are two types of loops in python.
characters or not.
5. Write a program which finds out whether a given name is present in a list or not. • while loops
6. Write a program to calculate the grade of a student from his marks from the • for loops
following scheme: We will look into these one by one.
90 – 100 => Ex
80 – 90 => A WHILE LOOP
70 – 80 => B
Syntax:
60 – 70 =>C
50 – 60 => D while (condition): # The block keeps executing until the condition is true
<50 => F #Body of the loop
7. Write a program to find out whether a given post is talking about “Harry” or not. In while loops, the condition is checked first. If it evaluates to true, the body of the loop
is executed otherwise not!
If the loop is entered, the process of [condition check & execution] is continued until
the condition becomes False.
Example:
i = 0
while i < 5: # print "Harry" – 5 times!
print("Harry")
i = i + 1
Note: If the condition never become false, the loop keeps getting executed.
Quick Quiz: Write a program to print the content of a list using while loops.
25 26
FOR LOOP Example:
A for loop is used to iterate through a sequence like list, tuple, or string [iterables] for i in range (0,80):
print(i) # this will print 0,1,2 and 3
Syntax: if i==3
break
l = [1, 7, 8]
for item in l: THE CONTINUE STATEMENT
print(item) # prints 1, 7 and 8
‘continue’ is used to stop the current iteration of the loop and continue with the next
RANGE FUNCTION IN PYTHON one. It instructs the Program to “skip this iteration”.
We can also specify the start, stop and step-size as follows: for i in range(4):
print("printing")
range(start, stop, step_size) if i == 2: # if i is 2, the iteration is skipped
# step_size is usually not used with range() continue
print(i)
AN EXAMPLE DEMONSTRATING RANGE () FUNCTION.
for i in range(0,7): # range(7) can also be used. PASS STATEMENT
print(i) # prints 0 to 6
pass is a null statement in python.
FOR LOOP WITH ELSE
It instructs to “do nothing”.
An optional else can be used with a for loop if the code is to be executed when the
Example:
loops exhausts.
l = [1,7,8]
Example: for item in l:
pass # without pass, the program will throw an error
l= [1,7,8]
for item in l:
print(item)
else:
print("done") # this is printed when the loop exhausts!
Output:
1
7
8
done
27 28
CHAPTER 7 – PRACTICE SET CHAPTER 8 – FUNCTIONS & RECURSIONS
1. Write a program to print multiplication table of a given number using for loop. A function is a group of statements performing a specific task.
2. Write a program to greet all the person names stored in a list ‘l’ and which starts
When a program gets bigger in size and its complexity grows, it gets difficult for a
with S.
program to keep track on which piece of code is doing what!
l = ["Harry", "Soham", "Sachin", "Rahul"]
3. Attempt problem 1 using while loop. A function can be reused by the programmer in a given program any number of
4. Write a program to find whether a given number is prime or not.
5. Write a program to find the sum of first n natural numbers using while loop. EXAMPLE AND SYNTAX OF A FUNCTION
6. Write a program to calculate the factorial of a given number using for loop.
The syntax of a function looks as follows:
7. Write a program to print the following star pattern.
* def func1():
*** print('hello')
***** for n = 3 This function can be called any number of times, anywhere in the program.
8. Write a program to print the following star pattern:
* FUNCTION CALL
**
Whenever we want to call a function, we put the name of the function followed by
*** for n = 3
parentheses as follows:
9. Write a program to print the following star pattern.
*** func1() # This is called function call.
* * for n = 3
***
FUNCTION DEFINITION
10. Write a program to print multiplication table of n using for loops in reversed The part containing the exact set of instructions which are executed during the function
order. call.
Quick Quiz: Write a program to greet a user with “Good day” using functions.
29 30
def greet(name): This works as follows:
gr = "hello"+ name
return gr
a = greet ("harry")
# a will now contain "hello harry"
If we specify name = “stranger” in the line containing def, this value is used when no
argument is passed.
Example:
RECURSION
Recursion is a function which calls itself.
Example:
def factorial(n)
if i == 0 or i==1: # base condition which doesn’t call the function
any further
return 1
else:
return n*factorial(n-1) # function calling itself
31 32
CHAPTER 8 – PRACTICE SET PROJECT 1: SNAKE, WATER, GUN GAME
1. Write a program using functions to find greatest of three numbers. We all have played snake, water gun game in our childhood. If you haven’t, google the
2. Write a python program using function to convert Celsius to Fahrenheit. rules of this game and write a python program capable of playing this game with the
3. How do you prevent a python print() function to print a new line at the end. user.
4. Write a recursive function to calculate the sum of first n natural numbers.
5. Write a python function to print first n lines of the following pattern:
***
** - for n = 3
*
33 34
CHAPTER 9 – FILE I/O # Close the file
f.close()
The random-access memory is volatile, and all its contents are lost once a program
terminates. In order to persist the data forever, we use files. OTHER METHODS TO READ THE FILE.
A file is data stored in a storage device. A python program can talk to the file by reading We can also use f.readline() function to read one full line at a time.
content from it and writing content to it.
f.readline() # Read one line from the file.
Python has an open() function for opening files. It takes 2 parameters: filename and
mode. WITH STATEMENT
# open("filename", "mode of opening(read mode by default)") The best way to open and close the file automatically is the with statement.
open("this.txt", "r")
# Open the file in read mode using 'with', which automatically closes the
file
with open("this.txt", "r") as f:
READING A FILE IN PYTHON # Read the contents of the file
# Open the file in read mode text = f.read()
f = open("this.txt", "r")
# Read its contents # Print the contents
text = f.read() print(text)
# Print its contents
print(text)
35 36
CHAPTER 9 – PRACTICE SET CHAPTER 10 - OBJECT ORIENTED PROGRAMMING
1. Write a program to read the text from a given file ‘poems.txt’ and find out Solving a problem by creating object is one of the most popular approaches in
whether it contains the word ‘twinkle’. programming. This is called object-oriented programming.
2. The game() function in a program lets a user play a game and returns the score
This concept focuses on using reusable code (DRY Principle).
as an integer. You need to read a file ‘Hi-score.txt’ which is either blank or
contains the previous Hi-score. You need to write a program to update the Hi- CLASS
score whenever the game() function breaks the Hi-score.
A class is a blueprint for creating object.
3. Write a program to generate multiplication tables from 2 to 20 and write it to the
different files. Place these files in a folder for a 13 – year old.
4. A file contains a word “Donkey” multiple times. You need to write a program
which replace this word with ##### by updating the same file.
5. Repeat program 4 for a list of such words to be censored.
6. Write a program to mine a log file and find out whether it contains ‘python’.
7. Write a program to find out the line number where python is present from ques 6.
8. Write a program to make a copy of a text file “this. txt”
9. Write a program to find out whether a file is identical & matches the content of
another file.
10. Write a program to wipe out the content of a file using python. Syntax:
11. Write a python program to rename a file to “renamed_by_ python.txt.
class Employee: # Class name is written in pascal case
# Methods & Variables
OBJECT
An object is an instantiation of a class. When class is defined, a template (info) is
defined. Memory is allocated only after object instantiation.
Objects of a given class can invoke the methods available to it without revealing the
implementation details to the user. – Abstractions & Encapsulation!
CLASS ATTRIBUTES
An attribute that belongs to the class rather than a particular object.
Example:
37 38
__INIT__() CONSTRUCTOR
__init__() is a special method which is first run as soon as the object is created.
class Employee:
company = "Google" # Specific to Each Class __init__() method is also known as constructor.
harry = Employee() # Object Instatiation
It takes ‘self’ argument and can also take further arguments.
harry.company
Employee.company = "YouTube" # Changing Class Attribute
For Example:
INSTANCE ATTRIBUTES
class Employee:
An attribute that belongs to the Instance (object). Assuming the class from the previous def __init__(self, name):
example: self.name=name
def getSalary(self):
harry.name = "harry" ...
harry.salary = "30k" # Adding instance attribute
harry = Employee("Harry")
Note: Instance attributes, take preference over class attributes during assignment &
retrieval.
SELF PARAMETER
self refers to the instance of the class. It is automatically passed with a function call
from an object.
class Employee:
company = "Google"
def getSalary(self):
print("Salary is not there")
STATIC METHOD
Sometimes we need a function that does not use the self-parameter. We can define a
static method like this:
39 40
CHAPTER 10 – PRACTICE SET CHAPTER 11 - INHERITANCE & MORE ON OOPS
1. Create a class “Programmer” for storing information of few programmers Inheritance is a way of creating a new class from an existing class.
working at Microsoft.
Syntax:
2. Write a class “Calculator” capable of finding square, cube and square root of a
number. class Employee: # Base class
3. Create a class with a class attribute a; create an object from it and set ‘a’ # Code
directly using ‘object.a = 0’. Does this change the class attribute?
4. Add a static method in problem 2, to greet the user with hello. class Programmer(Employee): # Derived or child class
# Code
5. Write a Class ‘Train’ which has methods to book a ticket, get status (no of seats)
and get fare information of train running under Indian Railways. We can use the method and attributes of ‘Employee’ in ‘Programmer’ object.
6. Can you change the self-parameter inside a class to something else (say Also, we can overwrite or add new attributes and methods in ‘Programmer’ class.
“harry”). Try changing self to “slf” or “harry” and see the effects.
TYPES OF INHERITANCE
• Single inheritance
• Multiple inheritance
• Multilevel inheritance
SINGLE INHERITANCE
Single inheritance occurs when child class inherits only a single parent class.
41 42
MULTIPLE INHERITANCE CLASS METHOD
Multiple Inheritance occurs when the child class inherits from more than one parent A class method is a method which is bound to the class and not the object of the class.
classes.
@classmethod decorator is used to create a class method.
Syntax:
@classmethod
def(cls,p1,p2):
@PROPERTY DECORATORS
Consider the following class:
class Employee:
@property
def name(self):
return self.ename
If e = Employee() is an object of class employee, we can print (e.name) to print the
ename by internally calling name() function.
@name.setter
def name (self,value):
self.ename = value
These methods are called when a given operator is used on the objects.
p1+p2 # p1.__add__(p2)
p1-p2 # p1.__sub__(p2)
p1*p2 # p1.__mul__(p2)
SUPER() METHOD p1/p2 # p1.__truediv__(p2)
p1//p2 # p1.__floordiv__(p2)
super() method is used to access the methods of a super class in the derived class.
Other dunder/magic methods in Python:
super().__init__()
# __init__() Calls constructor of the base class str__() # used to set what gets displayed upon calling str(obj)
43 44
__len__() # used to set what gets displayed upon calling.__len__() or CHAPTER 11- PRACTICE SET
len(obj)
1. Create a class (2-D vector) and use it to create another class representing a 3-D
vector.
2. Create a class ‘Pets’ from a class ‘Animals’ and further create a class ‘Dog’ from
‘Pets’. Add a method ‘bark’ to class ‘Dog’.
3. Create a class ‘Employee’ and add salary and increment properties to it.
7i + 8j +10k
7. Override the __len__() method on vector of problem 5 to display the dimension of the
vector.
45 46
PROJECT 2 – THE PERFECT GUESS CHAPTER 12 – ADVANCED PYTHON 1
We are going to write a program that generates a random number and asks the user to NEWLY ADDED FEATURES IN PYTHON
guess it.
Following are some of the newly added features in Python programming language
If the player’s guess is higher than the actual number, the program displays “Lower
number please”. Similarly, if the user’s guess is too low, the program prints “higher WALRUS OPERATOR
number please” When the user guesses the correct number, the program displays the
The walrus operator (:=), introduced in Python 3.8, allows you to assign values to
number of guesses the player used to arrive at the number.
variables as part of an expression. This operator, named for its resemblance to the eyes
Hint: Use the random module. and tusks of a walrus, is officially called the "assignment expression."
Type hints are added using the colon (:) syntax for variables and the -> syntax for
function return types.
# Usage
print(greeting("Alice")) # Output: Hello, Alice!
Python's typing module provides more advanced type hints, such as List, Tuple, Dict,
and Union.
You can import List, Tuple and Dict types from the typing module like this:
47 48
The syntax of types looks something like this: dict1 = {'a': 1, 'b': 2}
dict2 = {'b': 3, 'c': 4}
merged = dict1 | dict2
from typing import List, Tuple, Dict, Union print(merged) # Output: {'a': 1, 'b': 3, 'c': 4}
You can now use multiple context managers in a single with statement more cleanly
# List of integers
numbers: List[int] = [1, 2, 3, 4, 5] using the parenthesised context manager
with (
# Tuple of a string and an integer
open('file1.txt') as f1,
person: Tuple[str, int] = ("Alice", 30)
open('file2.txt') as f2
):
# Dictionary with string keys and integer values
# Process files
scores: Dict[str, int] = {"Alice": 90, "Bob": 85}
49 50
try: CHAPTER 12 – PRACTICE SET
# Somecode
except: 1. Write a program to open three files 1.txt, 2.txt and 3.txt if any these files are not
# Somecode present, a message without exiting the program must be printed prompting the same.
else:
# Code # This is executed only if the try was successful 2. Write a program to print third, fifth and seventh element from a list using enumerate
function.
TRY WITH FINALLY 3. Write a list comprehension to print a list which contains the multiplication table of a
user entered number.
Python offers a ‘finally’ clause which ensures execution of a piece of code inspective of
the exception. 4. Write a program to display a/b where a and b are integers. If b=0, display infinite by
handling the ‘ZeroDivisionError’.
If the module is being run directly from the command line, the ‘ __name__’ is set to
string “__main__”. Thus, this behaviour is used to check whether the module is run
directly or imported to another file.
LIST COMPREHENSIONS
List Comprehension is an elegant way to create lists based on existing lists.
list1 = [1,7,12,11,22,]
list2 = [i for item in list 1 if item > 8]
51 52
CHAPTER 13 – ADVANCED PYTHON 2 sum(1,2,3) # returns 6
We create a new environment using: Formats the values inside the string into a desired output.
The next step after creating the virtual environment is to activate it. Syntax:
We can now use this virtual environment as a separate Python installation. "{} is a good {}".format("harry", "boy") #1.
"{} is a good {o}".format("harry", "boy") #2.
PIP FREEZE COMMAND
# output for 1:
‘pip freeze’ returns all the package installed in a given python environment along with # harry is a good boy
the versions.
# output for 2:
pip freeze > requirements .txt # boy is a good harry
The above command creates a file named ‘requirements.txt’ in the same directory
containing the output of ‘pip freeze’. MAP, FILTER & REDUCE
We can distribute this file to other users, and they can recreate the same environment Map applies a function to all the items in an input_list.
using:
Syntax.
pip install –r requirements.txt
map(function, input_list)
LAMBDA FUNCTIONS # the function can be lambda function
Filter creates a list of items for which the function returns true.
Function created using an expression using ‘lambda’ keyword.
list(filter(function))
Syntax: # the function can be lambda function
53 54
If the function computes sum of two numbers and the list is [1,2,3,4] CHAPTER 13- PRACTICE SET
1. Create two virtual environments, install few packages in the first one. How do you
create a similar environment in the second one?
2. Write a program to input name, marks and phone number of a student and format it
using the format function like below:
“The name of the student is Harry, his marks are 72 and phone number is 99999888”
5. Write a program to find the maximum of the numbers in a list using the reduce
function.
6. Run pip freeze for the system interpreter. Take the contents and create a similar
virtualenv.
7. Explore the ‘Flask’ module and create a web server using Flask & Python.
55 56
MEGA PROJECT 1: JARVIS - VOICE-ACTIVATED VIRTUAL ASSISTANT 13. Processes commands to determine actions such as opening a website, playing
music, fetching news, or generating a response via OpenAI.
Jarvis is a voice-activated virtual assistant designed to perform tasks such as web
browsing, playing music, fetching news, and responding to user queries using OpenAI's LIBRARIES USED
GPT-3.5-turbo model.
• speech_recognition
FEATURES • webbrowser
• pyttsx3
• Voice Recognition • musicLibrary
• Utilizes the speech_recognition library to listen for and recognize voice commands. • requests
• Activates upon detecting the wake word "Jarvis." • openai
• Text-to-Speech • gTTS
• Converts text to speech using pyttsx3 for local conversion. • pygame
• Uses gTTS (Google Text-to-Speech) and pygame for playback. • os
• Web Browsing.
• Opens websites like Google, Facebook, YouTube, and LinkedIn based on voice
commands.
• Music Playback
• Interfaces with a musicLibrary module to play songs via web links.
• News Fetching
• Fetches and reads the latest news headlines using NewsAPI.
• OpenAI Integration
• Handles complex queries and generates responses using OpenAI's GPT-3.5-turbo.
• Acts as a general virtual assistant similar to Alexa or Google Assistant.
• Activates upon detecting the wake word "Jarvis."
• Text-to-Speech
WORKFLOW
1. Initialization
2. Greets the user with "Initializing Jarvis...."
3. Wake Word Detection
4. Listens for the wake word "Jarvis."
5. Acknowledges activation by saying "Ya."
6. Command Processing.
7. Processes commands to determine actions such as opening a website, playing
music, fetching news, or generating a response via OpenAI.
8. Speech Output.
9. Provides responses using speak function with either pyttsx3 or gTTS.
10. Greets the user with "Initializing Jarvis...."
11. Wake Word Detection
12. Acknowledges activation by saying "Ya."
57 58
MEGA PROJECT 2: AUTO-REPLY AI CHATBOT • Analyze the copied chat history to check if the last message is from a specific
user (e.g., "Rohan Das").
DESCRIPTION • If the last message is from the target user, send the chat history to OpenAI's
GPT-3.5-turbo to generate a humorous response.
This project automates the process of interacting with a chat application, specifically
• Copy the generated response to the clipboard.
designed to analyze chat history and generate humorous responses using OpenAI's
• Send Response
GPT-3.5-turbo model. The virtual assistant, named Naruto, is a character that roasts
• Click on the chat input area and paste the generated response.
people in a funny way, based on the chat history.
• Press 'Enter' to send the response.
FEATURES • Wait for a brief period to ensure the application is open and ready for interaction.
• Chat History Retrieval
14. Automated Chat Interaction
• Retrieve the copied text from the clipboard.
15. Uses pyautogui to perform mouse and keyboard operations, interacting with the
• Message Analysis
chat application without manual intervention.
• Analyze the copied chat history to check if the last message is from a specific
16. Chat History Analysis
user (e.g., "Rohan Das").
17. Copies chat history from the chat application and analyzes it to determine if the last
• Generate Response
message was sent by a specific user (e.g., "Rohan Das").
• Copy the generated response to the clipboard.
18. Humorous Response Generation
• Send Response
19. Integrates with OpenAI's GPT-3.5-turbo model to generate funny, roast-style
responses based on the analyzed chat history.
LIBRARIES USED
20. Clipboard Operations
21. Utilizes pyperclip to copy and paste text, facilitating the retrieval and insertion of 1. pyautogui: For automating mouse and keyboard interactions.
chat messages. 2. time: For adding delays between operations.
22. Uses pyautogui to perform mouse and keyboard operations, interacting with the 3. pyperclip: For clipboard operations.
chat application without manual intervention. 4. openai: For interacting with OpenAI's GPT-3.5-turbo model.
23. Copies chat history from the chat application and analyzes it to determine if the last
message was sent by a specific user (e.g., "Rohan Das").
24. Humorous Response Generation
25. Integrates with OpenAI's GPT-3.5-turbo model to generate funny, roast-style
responses based on the analyzed chat history.
WORKFLOW
• Initialization and Setup
• Click on the Chrome icon to open the chat application.
• Wait for a brief period to ensure the application is open and ready for interaction.
• Chat History Retrieval
• Periodically select and copy chat history by dragging the mouse over the chat
area and using the copy shortcut.
• Retrieve the copied text from the clipboard.
• Message Analysis
59 60