The Ultimate Python Handbook
The Ultimate Python Handbook
17
CONTENTS PYTHON PROGRAMMING HANDBOOK CHAPTER 1 – MODULES, COMMENTS & PIP
Tuples in Python ........................................................................................................................... 17
PREFACE ........................................................................................................................................... 1 Tuple Methods .............................................................................................................................. 17
Let’s write our very first python program. Create a file called hello.py and paste the
WHAT IS PROGRAMMING? below code in it.
Purpose and Audience .................................................................................................................... 1 Chapter 4 - Practice Set .................................................................................................................... 19
Structure and Content ..................................................................................................................... 1
Just like we use Hindi or English to communicate with each other, we use a
Chapter 5 – Dictionary & Sets ............................................................................................................ 20 print("hello world") # print is a function (more later)
programming language like Python to communicate with the computer.
Why Python?................................................................................................................................... 1 Properties of Python Dictionaries ................................................................................................... 20 Execute this file (.py file) by typing python hello.py and you will see Hello World printed
Acknowledgements ........................................................................................................................ 1 Dictionary Methods ....................................................................................................................... 20 Programming is a way to instruct the computer to perform various tasks. on the screen.
Conclusion ..................................................................................................................................... 1 Sets in Python. .............................................................................................................................. 20
Contents ........................................................................................................................................ 2
WHAT IS PYTHON? MODULES
Properties of Sets .......................................................................................................................... 21
Python programming Handbook .......................................................................................................... 6 Operations on sets ........................................................................................................................ 21 Python is a simple and easy to understand language which feels like reading simple A module is a file containing code written by somebody else (usually) which can be
What is Programming? .................................................................................................................... 6 Chapter 5 – Practice Set .................................................................................................................... 22 English. This Pseudo code nature is easy to learn and understandable by beginners. imported and used in our programs.
What is Python? .............................................................................................................................. 6 Chapter 6 – Conditional Expression ................................................................................................... 23
FEATURES OF PYTHON PIP
Features of Python .......................................................................................................................... 6 If Else and Elif in Python ................................................................................................................. 23
Installation ..................................................................................................................................... 6 Code example. ............................................................................................................................. 23 • Easy to understand = Less development time Pip is the package manager for python. You can use pip to install a module on your
Chapter 1 – Modules, Comments & pip ................................................................................................ 7 Relational Operators ..................................................................................................................... 24 • Free and open source system.
Modules ......................................................................................................................................... 7 Logical Operators ......................................................................................................................... 24
• High level language
pip install flask # Installs Flask Module
pip ................................................................................................................................................. 7 • Portable: Works on Linux / Windows / Mac.
Elif clause ..................................................................................................................................... 24
• Fun to work with! TYPES OF MODULES
Types of Modules ............................................................................................................................ 7 Important notes: ........................................................................................................................... 24
Using python as a calculator ............................................................................................................ 7 Chapter 6 – Practice Set .................................................................................................................... 25
There are two types of modules in Python.
INSTALLATION
Comments ..................................................................................................................................... 7 Chapter 7 – Loops in Python .............................................................................................................. 26 1. Built in Modules (Preinstalled in Python)
Types of Comments ........................................................................................................................ 7
Python can be easily installed from python.org. When you click on the download
Types of Loops in Python ............................................................................................................... 26 2. External Modules (Need to install using pip)
button, python can be installed right after you complete the setup by executing the file
Chapter 1 – Practice Set ...................................................................................................................... 9 While loop .................................................................................................................................... 26
for your platform. Some examples of built in modules are os, random etc.
Chapter 2 – Variables and Datatype ................................................................................................... 10 For loop ........................................................................................................................................ 27
Data Types ................................................................................................................................... 10 range() Function in Python ............................................................................................................. 27 Some examples of external modules are tensorflow, flask etc.
Rules for choosing an identifier ...................................................................................................... 10 An Example Demonstrating range() function. .................................................................................. 27
USING PYTHON AS A CALCULATOR
Operators in Python ...................................................................................................................... 10 For Loop with Else ......................................................................................................................... 27
type() function and typecasting. ..................................................................................................... 11 The Break Statement ..................................................................................................................... 27 We can use python as a calculator by typing “python” + ↵ on the terminal.
input() Function ............................................................................................................................ 11 The Continue Statement ................................................................................................................ 28
This opens REPL or Read Evaluate Print Loop.
Chapter 2 – Practice Set .................................................................................................................... 12 Pass statement ............................................................................................................................. 28
Chapter 3 – Strings ........................................................................................................................... 13 Chapter 7 – Practice Set .................................................................................................................... 29 COMMENTS
String Slicing ................................................................................................................................. 13 Chapter 8 – Functions & Recursions .................................................................................................. 30
Comments are used to write something which the programmer does not want to
Slicing With Skip Value .................................................................................................................. 14 Example and syntax of a function ................................................................................................... 30 execute. This can be used to mark author name, date etc.
String Functions ............................................................................................................................ 14 Function call................................................................................................................................. 30
Escape Sequence Characters ........................................................................................................ 15 Function Definition ....................................................................................................................... 30 TYPES OF COMMENTS
Chapter 3 – Practice Set .................................................................................................................... 16 Types of Functions in Python ......................................................................................................... 30 There are two types of comments in python.
Chapter 4 – Lists And Tuples ............................................................................................................. 17 Functions with Arguments ............................................................................................................. 30
List Indexing ................................................................................................................................. 17 Default Parameter Value ............................................................................................................... 31
2 3 6 7
Recursion ..................................................................................................................................... 31 Types Definitions in Python ............................................................................................................ 48
PREFACE Chapter 8 – Practice Set .................................................................................................................... 33 Advanced Type Hints ..................................................................................................................... 48
Welcome to the “Ultimate Python Programming Handbook," your comprehensive guide to Project 1: Snake, Water, Gun Game ................................................................................................... 34 Match Case .................................................................................................................................. 49
mastering Python programming. This handbook is designed for beginners and anyone looking to Chapter 9 – File I/O ........................................................................................................................... 35 Dictionary Merge & Update Operators ............................................................................................ 49
strengthen their foundational knowledge of Python, a versatile and user-friendly programming
Type of Files. ................................................................................................................................. 35 Exception handling in Python ......................................................................................................... 50
language.
Opening a File ............................................................................................................................... 35 Raising Exceptions ........................................................................................................................ 50
PURPOSE AND AUDIENCE Reading a File in Python ................................................................................................................. 35 try with else clause ....................................................................................................................... 50
This handbook aims to make programming accessible and enjoyable for everyone. Whether Other methods to read the file. ...................................................................................................... 36 try with finally ............................................................................................................................... 51
you're a student new to coding, a professional seeking to enhance your skills, or an enthusiast Modes of opening a file .................................................................................................................. 36 If __name__== ‘__main__’ in python ................................................................................................ 51
exploring Python, this handbook will definitely be helpful. Python's simplicity and readability Write Files in Python ...................................................................................................................... 36 The global keyword ....................................................................................................................... 51
make it an ideal starting point for anyone interested in programming.
With Statement ............................................................................................................................. 36 enumerate function in python ........................................................................................................ 51
STRUCTURE AND CONTENT Chapter 9 – Practice Set .................................................................................................................... 37 List comprehensions ..................................................................................................................... 51
Chapter 10 - Object Oriented Programming ....................................................................................... 38 Chapter 12 – Practice set .................................................................................................................. 52
The handbook is divided into clear, concise chapters, each focused on a specific aspect of
Python: Class............................................................................................................................................ 38 Chapter 13 – Advanced Python 2 ....................................................................................................... 53
Object .......................................................................................................................................... 38 Virtual envirionment ...................................................................................................................... 53
• Fundamental Concepts: Start with the basics, such as installing Python and writing your
Modelling a problem in OOPs......................................................................................................... 38 Installation ................................................................................................................................... 53
first program.
• Practical Examples: Illustrative examples and sample code demonstrate the Class Attributes ............................................................................................................................ 38 pip freeze command ..................................................................................................................... 53
application of concepts. Instance attributes ........................................................................................................................ 39 Lambda functions ......................................................................................................................... 53
• Hands-On Exercises: End-of-chapter exercises reinforce learning and build confidence. self parameter .............................................................................................................................. 39 join method (strings) ..................................................................................................................... 54
• Additional Resources: References to official Python documentation for deeper
static method ............................................................................................................................... 39 format method (strings) ................................................................................................................. 54
exploration.
__init__() constructor ..................................................................................................................... 40 Map, Filter & Reduce ..................................................................................................................... 54
WHY PYTHON? Chapter 10 – Practice Set .................................................................................................................. 41 Chapter 13 – Practice Set .................................................................................................................. 56
Python is known for its simplicity and readability, making it perfect for beginners. It is a high- Chapter 11 - Inheritance & more on OOPs .......................................................................................... 42 MEGA Project 1: Jarvis ...................................................................................................................... 57
level, interpreted language with a broad range of libraries and frameworks, supporting Types of Inheritance ...................................................................................................................... 42 Features ....................................................................................................................................... 57
applications in web development, data analysis, AI, and more. Python's versatility and ease of Single Inheritance ......................................................................................................................... 42 Workflow ...................................................................................................................................... 57
use make it a valuable tool for both novice and experienced programmers.
Multiple Inheritance ...................................................................................................................... 43 Libraries Used............................................................................................................................... 58
ACKNOWLEDGEMENTS Multilevel Inheritance .................................................................................................................... 43 Mega Project 2: Auto Reply AI Chatbot ............................................................................................... 59
super() method ............................................................................................................................. 43 Description ................................................................................................................................... 59
I extend my gratitude to the educators, programmers, and contributors who have shared their
knowledge and insights, shaping the content of this handbook. Special thanks to all the class method ................................................................................................................................ 44 Features ....................................................................................................................................... 59
students watching my content on YouTube and Python community for maintaining a supportive @property Decorators ................................................................................................................... 44 Workflow ...................................................................................................................................... 59
and inspiring environment for learners worldwide. @.getters and @.setters ................................................................................................................ 44 Libraries Used............................................................................................................................... 60
Operator Overloading in Python ..................................................................................................... 44
CONCLUSION
Chapter 11- Practice set ................................................................................................................... 46
Learning programming can be both exciting and challenging. The “Ultimate Python
Project 2 – The Perfect Guess ............................................................................................................ 47
Programming Handbook" aims to make your journey smooth and rewarding. Watch my video
along with following this handbook for optimal learning. Let this guide be your stepping stone to Chapter 12 – Advanced Python 1 ....................................................................................................... 48
success in the world of programming. Newly added features in python ..................................................................................................... 48
Walrus Operator ........................................................................................................................... 48
1 4 5
CHAPTER 2 – VARIABLES AND DATATYPE TYPE() FUNCTION AND TYPECASTING. SLICING WITH SKIP VALUE index = str.find("rr")
print(index) # Output: 2
A variable is the name given to a memory location in a program. For example. type() function is used to find the data type of a given variable in python. We can provide a skip value as a part of our slice like this: 6. string.replace (old word, new word ) – This function replace the old word with
new word in the entire string.
a= 30 # variables = container to store a value. a = 31 word = "amazing"
b= "harry" # keywords = reserved words in python type(a) # class <int> str = "harry"
c= 71.22 # identifiers = class/function/variable name word[1: 6: 2] # "mzn"
replaced_string = str.replace("r", "l")
b = "31"
DATA TYPES Other advanced slicing techniques: print(replaced_string) # Output: "hally"
type (b) # class <str>
Primarily these are the following data types in Python: A number can be converted into a string and vice versa (if possible) Word = "amazing"
Word = [:7] # word [0:7] – 'amazing'
1. Integers There are many functions to convert one data type into another. Word = [0:] # word [0:7] – 'amazing'
2. Floating point numbers
ESCAPE SEQUENCE CHARACTERS
str(31) =>"31" # integer to string conversion
3. Strings int("32") => 32 # string to integer conversion Sequence of characters after backslash "\" → Escape Sequence characters
4. Booleans float(32) => 32.0 # integer to float conversion
STRING FUNCTIONS
5. None Escape Sequence characters comprise of more than one character but represent one
… and so, on Some of the commonly used functions to perform operations on or manipulate strings
character when used within the strings.
Python is a fantastic language that automatically identifies the type of data for us. are as follows. Let us assume there is a string ‘str’ as follows:
Here "31" is a string literal and 31 a numeric literal.
a= 71 # identifies a as class <int> str = 'harry'
b=88.44 # identifies b as class <float> INPUT () FUNCTION Now when operated on this string ‘str’, these functions do the following:
name= "harry" # identifies name as class <str>
This function allows the user to take input from the keyboard as a string. 1. len () function – This function returns the length of the strings.
RULES FOR CHOOSING AN IDENTIFIER
A = input ("enter name") # if a is "harry", the user entered harry
str = "harry"
• A variable name can contain alphabets, digits, and underscores. It is important to note that the output of input is always a string (even is a number is print(len(str)) # Output: 5
• A variable name can only start with an alphabet and underscores. entered). 2. String.endswith("rry") – This function_ tells whether the variable string ends with
• A variable name can’t start with a digit. the string "rry" or not. If string is "harry", it returns true for "rry" since Harry ends
• No while space is allowed to be used inside a variable name. with rry.
Examples of a few variable names are: harry, one8, seven, _seven etc. str = "harry"
print(str.endswith("rry")) # Output: True
OPERATORS IN PYTHON 3. string.count("c") – counts the total number of occurrences of any character.
Following are some common operators in python:
str = "harry"
count = str.count("r")
1. Arithmetic operators: +, -, *, / etc.
print(count) # Output: 2
2. Assignment operators: =, +=, -= etc.
4. the first character of a given string.
3. Comparison operators: ==, >, >=, <, != etc.
4. Logical operators: and, or, not. 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.
str = "harry"
10 11 14 15
1. Single Line Comments: To write a single line comment just add a ‘#’ at the start CHAPTER 1 – PRACTICE SET CHAPTER 2 – PRACTICE SET CHAPTER 3 – STRINGS
of the line.
# This is a Single-Line Comment 1. Write a program to print Twinkle twinkle little star poem in python. 1. Write a python program to add two numbers. String is a data type in python.
2. Use REPL and print the table of 5 using it. 2. Write a python program to find remainder when a number is divided by z.
String is a sequence of characters enclosed in quotes.
2. Multiline Comments: To write multi-line comments you can use ‘#’ at each line 3. Install an external module and use it to perform an operation of your interest. 3. Check the type of variable assigned using input () function.
or you can use the multiline string (""" """) 4. Write a python program to print the contents of a directory using the os module. 4. Use comparison operator to find out whether ‘a’ given variable a is greater than We can primarily write a string in these three ways.
"""This is an amazing Search online for the function which does that. ‘b’ or not. Take a = 34 and b = 80
a ='harry' # Single quoted string
example of a Multiline 5. Label the program written in problem 4 with comments. 5. Write a python program to find an average of two numbers entered by the user.
b = "harry" # Double quoted string
comment!""" 6. Write a python program to calculate the square of a number entered by the user. c = '''harry''' # Triple quoted string
STRING SLICING
A string in python can be sliced for getting a part of the strings.
Consider the following string:
The index in a sting starts from 0 to (length -1) in Python. In order to slice a string, we use
the following syntax:
Negative Indices: Negative indices can also be used as shown in the figure above. -1
corresponds to the (length - 1) index, -2 to (length - 2).
8 9 12 13
a = (1, 7, 2) CHAPTER 4 - PRACTICE SET CHAPTER 5 – PRACTICE SET CHAPTER 6 – CONDITIONAL EXPRESSION
• a.count (1): a count (1) will return number of times 1 occurs in a.
1. Write a program to store seven fruits in a list entered by the user. 1. Write a program to create a dictionary of Hindi words with values as their English Sometimes we want to play PUBG on our phone if the day is Sunday.
• a.index (1) will return the index of first occurrence of 1 in a.
2. Write a program to accept marks of 6 students and display them in a sorted translation. Provide user with an option to look it up!
manner. Sometimes we order Ice Cream online if the day is sunny.
2. Write a program to input eight numbers from the user and display all the unique
3. Check that a tuple type cannot be changed in python. numbers (once). Sometimes we go hiking if our parents allow.
4. Write a program to sum a list with 4 numbers. 3. Can we have a set with 18 (int) and '18' (str) as a value in it?
5. Write a program to count the number of zeros in the following tuple: 4. What will be the length of following set s: All these are decisions which depend on a condition being met.
a = (7, 0, 8, 0, 0, 9) s = set()
In python programming too, we must be able to execute instructions on a condition(s)
s.add(20)
s.add(20.0)
being met.
s.add('20') # length of s after these operations?
This is what conditionals are for!
5. s = {}
What is the type of 's'?
IF ELSE AND ELIF IN PYTHON
6. Create an empty dictionary. Allow 4 friends to enter their favorite language as
value and use key as their names. Assume that the names are unique. If else and elif statements are a multiway decision taken by our program due to certain
7. If the names of 2 friends are same; what will happen to the program in problem conditions in our code.
6?
Syntax:
8. If languages of two friends are same; what will happen to the program in problem
if (condition1): # if condition1 is True
6? print ("yes")
9. Can you change the values inside a list which is contained in set S?
s = {8, 7, 12, "Harry", [1,2]} elif(condition2): # if condition2 is True
print("no")
else: # otherwise
print("maybe")
CODE EXAMPLE.
a=22
if(a>9):
print("greater")
else:
print("lesser")
Quick Quiz: Write a program to print yes when the age entered by the user is greater
than or equal to 18.
18 19 22 23
CHAPTER 3 – PRACTICE SET CHAPTER 4 – LISTS AND TUPLES CHAPTER 5 – DICTIONARY & SETS If you are a programming beginner without much knowledge of mathematical
operations on sets, you can simply look at sets in python as data types containing
1. Write a python program to display a user entered name followed by Good Python lists are containers to store a set of values of any data type. Dictionary is a collection of keys-value pairs. unique values.
Afternoon using input () function.
Syntax:
2. Write a program to fill in a letter template given below with name and date. PROPERTIES OF SETS
letter = ''' a = {
Dear <|Name|>, 1. Sets are unordered => Element’s order doesn’t matter
"key": "value",
You are selected! "harry": "code", 2. Sets are unindexed => Cannot access elements by index
<|Date|> "marks": "100", 3. There is no way to change items in sets.
''' "list": [1, 2, 9] 4. Sets cannot contain duplicate values.
}
3. Write a program to detect double space in a string. OPERATIONS ON SETS
4. Replace the double space from problem 3 with single spaces. print(a["key"]) # Output: "value"
LIST INDEXING print(a["list"]) # Output: [1, 2, 9] Consider the following set:
5. Write a program to format the following letter using escape sequence
characters. A list can be indexed just like a string. s = {1,8,2,3}
letter = "Dear Harry, this python course is nice. Thanks!" PROPERTIES OF PYTHON DICTIONARIES • len(s): Returns 4, the length of the set
l1 = [7,9,"harry"]
1. It is unordered. • s.remove(8): Updates the set s and removes 8 from s.
l1[0] # 7
2. It is mutable. • s.pop(): Removes an arbitrary element from the set and return the element
l1[1] # 9
l1[70] # error 3. It is indexed. removed.
l1[0:2] # [7,9] #list slicing 4. Cannot contain duplicate keys. • s.clear():empties the set s.
• s.union({8,11}): Returns a new set with all items from both sets. {1,8,2,3,11}.
LIST METHODS.
DICTIONARY METHODS • s.intersection({8,11}): Return a set which contains only item in both sets {8}.
Consider the following list:
Consider the following dictionary.
l1 = [1,8,7,2,21,15]
a={"name":"harry"
• l1.sort(): updates the list to [1,2,7,8,15,21] "from":"india"
• l1.reverse(): updates the list to [15,21,2,7,8,1] "marks":[92,98,96]}
• l1.append(8): adds 8 at the end of the list • a.items(): Returns a list of (key,value)tuples.
• l1.insert(3,8): This will add 8 at 3 index • a.keys(): Returns a list containing dictionary's keys.
• l1.pop(2): Will delete element at index 2 and return its value. • a.update({"friends":}): Updates the dictionary with supplied key-value pairs.
• l1.remove(21): Will remove 21 from the list. • a.get("name"): Returns the value of the specified keys (and value is returned
eg."harry" is returned here).
TUPLES IN PYTHON
More methods are available on docs.python.org
A tuple is an immutable data type in python.
a = () # empty tuple
SETS IN PYTHON.
a = (1,) # tuple with only one element needs a comma
a = (1,7,2) # tuple with more than one element Set is a collection of non-repetitive elements.
s = set() # no repetition allowed!
TUPLE METHODS s.add(1)
s.add(2) # or set ={1,2}
Consider the following tuple.
16 17 20 21
CHAPTER 7 – LOOPS IN PYTHON FOR LOOP CHAPTER 8 – FUNCTIONS & RECURSIONS def greet(name):
gr = "hello"+ name
Sometimes we want to repeat a set of statements in our program. For instance: Print 1 A for loop is used to iterate through a sequence like list, tuple, or string [iterables] A function is a group of statements performing a specific task. return gr
to 1000.
Syntax: When a program gets bigger in size and its complexity grows, it gets difficult for a a = greet ("harry")
Loops make it easy for a programmer to tell the computer which set of instructions to program to keep track on which piece of code is doing what! # a will now contain "hello harry"
l = [1, 7, 8]
repeat and how!
for item in l: A function can be reused by the programmer in a given program any number of
print(item) # prints 1, 7 and 8 DEFAULT PARAMETER VALUE
TYPES OF LOOPS IN PYTHON
RANGE FUNCTION IN PYTHON EXAMPLE AND SYNTAX OF A FUNCTION We can have a value as default as default argument in a function.
Primarily there are two types of loops in python.
The range() function in python is used to generate a sequence of number. The syntax of a function looks as follows:
If we specify name = “stranger” in the line containing def, this value is used when no
• while loops argument is passed.
We can also specify the start, stop and step-size as follows: def func1():
• for loops print('hello')
Example:
We will look into these one by one. range(start, stop, step_size) This function can be called any number of times, anywhere in the program.
# step_size is usually not used with range() def greet(name = "stranger"):
WHILE LOOP AN EXAMPLE DEMONSTRATING RANGE () FUNCTION. FUNCTION CALL # function body
greet() # name will be "stranger" in function body (default)
Syntax: for i in range(0,7): # range(7) can also be used. Whenever we want to call a function, we put the name of the function followed by greet("harry") # name will be "harry" in function body (passed)
parentheses as follows:
while (condition): # The block keeps executing until the condition is true print(i) # prints 0 to 6
#Body of the loop func1() # This is called function call.
In while loops, the condition is checked first. If it evaluates to true, the body of the loop
FOR LOOP WITH ELSE RECURSION
FUNCTION DEFINITION
is executed otherwise not! An optional else can be used with a for loop if the code is to be executed when the Recursion is a function which calls itself.
loops exhausts. The part containing the exact set of instructions which are executed during the function
If the loop is entered, the process of [condition check & execution] is continued until It is used to directly use a mathematical formula as function.
call.
the condition becomes False. Example:
Quick Quiz: Write a program to greet a user with “Good day” using functions. Example:
Quick Quiz: Write a program to print 1 to 50 using a while loop. l= [1,7,8]
for item in l: factorial(n) = n x factorial (n-1)
Example: TYPES OF FUNCTIONS IN PYTHON
print(item) This function can be defined as follows:
else: There are two types of functions in python:
i = 0 print("done") # this is printed when the loop exhausts! def factorial(n)
while i < 5: # print "Harry" – 5 times!
Output: • Built in functions (Already present in python) if i == 0 or i==1: # base condition which doesn’t call the function
print("Harry") any further
i = i + 1 1 • User defined functions (Defined by the user)
return 1
7
Examples of built in functions includes len(), print(), range() etc. else:
8
Note: If the condition never become false, the loop keeps getting executed. return n*factorial(n-1) # function calling itself
done
The func1() function we defined is an example of user defined function.
Quick Quiz: Write a program to print the content of a list using while loops.
FUNCTIONS WITH ARGUMENTS
THE BREAK STATEMENT A function can accept some value it can work with. We can put these values in the
‘break’ is used to come out of the loop when encountered. It instructs the program to – parentheses.
exit the loop now.
A function can also return value as shown below:
26 27 30 31
RELATIONAL OPERATORS CHAPTER 6 – PRACTICE SET Example: CHAPTER 7 – PRACTICE SET
Relational Operators are used to evaluate conditions inside the if statements. Some 1. Write a program to find the greatest of four numbers entered by the user. for i in range (0,80): 1. Write a program to print multiplication table of a given number using for loop.
print(i) # this will print 0,1,2 and 3
examples of relational operators are: 2. Write a program to find out whether a student has passed or failed if it requires a 2. Write a program to greet all the person names stored in a list ‘l’ and which starts
if i==3
total of 40% and at least 33% in each subject to pass. Assume 3 subjects and break with S.
==: equals.
take marks as an input from the user. l = ["Harry", "Soham", "Sachin", "Rahul"]
3. A spam comment is defined as a text containing following keywords: THE CONTINUE STATEMENT 3. Attempt problem 1 using while loop.
> =: greater than/ equal to.
“Make a lot of money”, “buy now”, “subscribe this”, “click this”. Write a program ‘continue’ is used to stop the current iteration of the loop and continue with the next 4. Write a program to find whether a given number is prime or not.
< =: lesser than/ equal to. to detect these spams. 5. Write a program to find the sum of first n natural numbers using while loop.
one. It instructs the Program to “skip this iteration”.
4. Write a program to find whether a given username contains less than 10 6. Write a program to calculate the factorial of a given number using for loop.
LOGICAL OPERATORS characters or not. Example: 7. Write a program to print the following star pattern.
In python logical operators operate on conditional statements. For Example: 5. Write a program which finds out whether a given name is present in a list or not. *
for i in range(4):
6. Write a program to calculate the grade of a student from his marks from the print("printing") ***
• and – true if both operands are true else false. following scheme: if i == 2: # if i is 2, the iteration is skipped ***** for n = 3
• or – true if at least one operand is true or else false. 90 – 100 => Ex continue 8. Write a program to print the following star pattern:
• not – inverts true to false & false to true. 80 – 90 => A print(i) *
70 – 80 => B **
ELIF CLAUSE 60 – 70 =>C PASS STATEMENT *** for n = 3
elif in python means [else if]. An if statements can be chained together with a lot of 50 – 60 => D 9. Write a program to print the following star pattern.
<50 => F pass is a null statement in python. ***
these elif statements followed by an else statement.
7. Write a program to find out whether a given post is talking about “Harry” or not. It instructs to “do nothing”. * * for n = 3
if (condition1): ***
#code Example: 10. Write a program to print multiplication table of n using for loops in reversed
elif (condition2): # this ladder will stop once a condition in an if or l = [1,7,8] order.
elif is met. for item in l:
#code pass # without pass, the program will throw an error
elif(condition3):
#code
else:
#code
IMPORTANT NOTES:
1. There can be any number of elif statements.
2. Last else is executed only if all the conditions inside elifs fail.
24 25 28 29
PROJECT 1: SNAKE, WATER, GUN GAME CHAPTER 9 – FILE I/O CHAPTER 10 - OBJECT ORIENTED PROGRAMMING
We all have played snake, water gun game in our childhood. If you haven’t, google the The random-access memory is volatile, and all its contents are lost once a program Solving a problem by creating object is one of the most popular approaches in
rules of this game and write a python program capable of playing this game with the terminates. In order to persist the data forever, we use files. programming. This is called object-oriented programming. class Employee:
user. company = "Google" # Specific to Each Class
A file is data stored in a storage device. A python program can talk to the file by reading This concept focuses on using reusable code (DRY Principle). harry = Employee() # Object Instatiation
content from it and writing content to it. harry.company
CLASS Employee.company = "YouTube" # Changing Class Attribute
A class is a blueprint for creating object. INSTANCE ATTRIBUTES
An attribute that belongs to the Instance (object). Assuming the class from the previous
example:
harry.name = "harry"
harry.salary = "30k" # Adding instance attribute
Note: Instance attributes, take preference over class attributes during assignment &
retrieval.
When looking up for harry.attribute it checks for the following:
Syntax:
1) Is attribute present in object?
class Employee: # Class name is written in pascal case
TYPE OF FILES. # Methods & Variables
2) Is attribute present in class?
There are 2 types of files:
OBJECT SELF PARAMETER
1. Text files (.txt, .c, etc)
2. Binary files (.jpg, .dat, etc) An object is an instantiation of a class. When class is defined, a template (info) is self refers to the instance of the class. It is automatically passed with a function call
defined. Memory is allocated only after object instantiation. from an object.
Python has a lot of functions for reading, updating, and deleting files.
Objects of a given class can invoke the methods available to it without revealing the harry.getSalary() # here self is harry
OPENING A FILE implementation details to the user. – Abstractions & Encapsulation! # equivalent to Employee.getSalary(harry)
The function getSalary() is defined as:
Python has an open() function for opening files. It takes 2 parameters: filename and
MODELLING A PROBLEM IN OOPS
mode. class Employee:
We identify the following in our problem. company = "Google"
# open("filename", "mode of opening(read mode by default)") def getSalary(self):
open("this.txt", "r") • Noun → Class → Employee print("Salary is not there")
• Adjective → Attributes → name, age, salary
STATIC METHOD
• Verbs → Methods → getSalary(), increment()
READING A FILE IN PYTHON
Sometimes we need a function that does not use the self-parameter. We can define a
# Open the file in read mode CLASS ATTRIBUTES static method like this:
f = open("this.txt", "r")
# Read its contents An attribute that belongs to the class rather than a particular object. @staticmethod # decorator to mark greet as a static method
text = f.read() def greet():
# Print its contents Example: print("Hello user")
print(text)
34 35 38 39
This works as follows: CHAPTER 8 – PRACTICE SET # Close the file CHAPTER 9 – PRACTICE SET
f.close()
1. Write a program using functions to find greatest of three numbers. 1. Write a program to read the text from a given file ‘poems.txt’ and find out
2. Write a python program using function to convert Celsius to Fahrenheit. OTHER METHODS TO READ THE FILE. whether it contains the word ‘twinkle’.
3. How do you prevent a python print() function to print a new line at the end. 2. The game() function in a program lets a user play a game and returns the score
4. Write a recursive function to calculate the sum of first n natural numbers. We can also use f.readline() function to read one full line at a time. as an integer. You need to read a file ‘Hi-score.txt’ which is either blank or
5. Write a python function to print first n lines of the following pattern: contains the previous Hi-score. You need to write a program to update the Hi-
f.readline() # Read one line from the file.
*** score whenever the game() function breaks the Hi-score.
** - for n = 3 MODES OF OPENING A FILE 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.
r – open for reading
4. A file contains a word “Donkey” multiple times. You need to write a program
6. Write a python function which converts inches to cms. w - open for writing which replace this word with ##### by updating the same file.
7. Write a python function to remove a given word from a list ad strip it at the same 5. Repeat program 4 for a list of such words to be censored.
a - open for appending
time. 6. Write a program to mine a log file and find out whether it contains ‘python’.
8. Write a python function to print multiplication table of a given number. + - open for updating. 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”
The programmer needs to be extremely careful while working with recursion to ensure ‘rb’ will open for read in binary mode. 9. Write a program to find out whether a file is identical & matches the content of
that the function doesn’t infinitely keep calling itself. Recursion is sometimes the most another file.
‘rt’ will open for read in text mode.
direct way to code an algorithm. 10. Write a program to wipe out the content of a file using python.
WRITE FILES IN PYTHON 11. Write a python program to rename a file to “renamed_by_ python.txt.
In order to write to a file, we first open it in write or append mode after which, we use
the python’s f.write() method to write to the file!
# Open the file in write mode
f = open("this.txt", "w")
# Write a string to the file
f.write("this is nice")
# Close the file
f.close()
WITH STATEMENT
The best way to open and close the file automatically is the with statement.
# Open the file in read mode using 'with', which automatically closes the
file
with open("this.txt", "r") as f:
# Read the contents of the file
text = f.read()
# Print the contents
print(text)
32 33 36 37
CHAPTER 11 - INHERITANCE & MORE ON OOPS MULTIPLE INHERITANCE CHAPTER 11- PRACTICE SET PROJECT 2 – THE PERFECT GUESS
Inheritance is a way of creating a new class from an existing class. Multiple Inheritance occurs when the child class inherits from more than one parent 1. Create a class (2-D vector) and use it to create another class representing a 3-D We are going to write a program that generates a random number and asks the user to
classes. vector. guess it.
Syntax:
2. Create a class ‘Pets’ from a class ‘Animals’ and further create a class ‘Dog’ from If the player’s guess is higher than the actual number, the program displays “Lower
class Employee: # Base class
‘Pets’. Add a method ‘bark’ to class ‘Dog’. number please”. Similarly, if the user’s guess is too low, the program prints “higher
# Code
number please” When the user guesses the correct number, the program displays the
3. Create a class ‘Employee’ and add salary and increment properties to it.
class Programmer(Employee): # Derived or child class number of guesses the player used to arrive at the number.
# Code Write a method ‘salaryAfterIncrement’ method with a @property decorator with a setter
Hint: Use the random module.
We can use the method and attributes of ‘Employee’ in ‘Programmer’ object. which changes the value of increment based on the salary.
Also, we can overwrite or add new attributes and methods in ‘Programmer’ class. 4. Write a class ‘Complex’ to represent complex numbers, along with overloaded
operators ‘+’ and ‘*’ which adds and multiplies them.
TYPES OF INHERITANCE
5. Write a class vector representing a vector of n dimensions. Overload the + and *
• Single inheritance operator which calculates the sum and the dot(.) product of them.
• Multiple inheritance
• Multilevel inheritance 6. Write __str__() method to print the vector as follows:
7i + 8j +10k
SINGLE INHERITANCE
MULTILEVEL INHERITANCE Assume vector of dimension 3 for this problem.
Single inheritance occurs when child class inherits only a single parent class.
When a child class becomes a parent for another child class. 7. Override the __len__() method on vector of problem 5 to display the dimension of the
vector.
SUPER() METHOD
super() method is used to access the methods of a super class in the derived class.
super().__init__()
# __init__() Calls constructor of the base class
42 43 46 47
__INIT__() CONSTRUCTOR CHAPTER 10 – PRACTICE SET CLASS METHOD __len__() # used to set what gets displayed upon calling.__len__() or
len(obj)
__init__() is a special method which is first run as soon as the object is created. 1. Create a class “Programmer” for storing information of few programmers A class method is a method which is bound to the class and not the object of the class.
working at Microsoft.
__init__() method is also known as constructor. @classmethod decorator is used to create a class method.
2. Write a class “Calculator” capable of finding square, cube and square root of a
It takes ‘self’ argument and can also take further arguments. number. Syntax:
3. Create a class with a class attribute a; create an object from it and set ‘a’
For Example: directly using ‘object.a = 0’. Does this change the class attribute? @classmethod
def(cls,p1,p2):
4. Add a static method in problem 2, to greet the user with hello.
class Employee:
def __init__(self, name): 5. Write a Class ‘Train’ which has methods to book a ticket, get status (no of seats)
self.name=name and get fare information of train running under Indian Railways. @PROPERTY DECORATORS
def getSalary(self): 6. Can you change the self-parameter inside a class to something else (say
...
Consider the following class:
“harry”). Try changing self to “slf” or “harry” and see the effects.
class Employee:
harry = Employee("Harry")
@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.
@.GETTERS AND @.SETTERS
The method name with ‘@property’ decorator is called getter method.
We can define a function + @ name.setter decorator like below:
@name.setter
def name (self,value):
self.ename = value
OPERATOR OVERLOADING IN PYTHON
Operators in Python can be overloaded using dunder methods.
These methods are called when a given operator is used on the objects.
Operators in Python can be overloaded using the following methods:
p1+p2 # p1.__add__(p2)
p1-p2 # p1.__sub__(p2)
p1*p2 # p1.__mul__(p2)
p1/p2 # p1.__truediv__(p2)
p1//p2 # p1.__floordiv__(p2)
Other dunder/magic methods in Python:
str__() # used to set what gets displayed upon calling str(obj)
40 41 44 45
dict1 = {'a': 1, 'b': 2} try: sum(1,2,3) # returns 6 If the function computes sum of two numbers and the list is [1,2,3,4]
dict2 = {'b': 3, 'c': 4} # Somecode
merged = dict1 | dict2 except: JOIN METHOD (STRINGS)
print(merged) # Output: {'a': 1, 'b': 3, 'c': 4} # Somecode
Creates a string from iterable objects.
You can now use multiple context managers in a single with statement more cleanly else:
# Code # This is executed only if the try was successful
using the parenthesised context manager l = ["apple", "mango", "banana"]
result = ", and, ".join(l)
with ( print(result)
open('file1.txt') as f1, TRY WITH FINALLY The above line will return “apple,and,mango,and,banana”.
open('file2.txt') as f2
): Python offers a ‘finally’ clause which ensures execution of a piece of code inspective of
# Process files the exception. FORMAT METHOD (STRINGS)
Formats the values inside the string into a desired output.
template.format(p1,p2...)
try:
EXCEPTION HANDLING IN PYTHON # Some Code Syntax:
except:
There are many built-in exceptions which are raised in python when something goes # Some Code "{} is a good {}".format("harry", "boy") #1.
wrong. finally: "{} is a good {o}".format("harry", "boy") #2.
# Some Code # Executed regardless of error!
Exception in python can be handled using a try statement. The code that handles the # output for 1:
exception is written in the except clause. IF __NAME__== ‘__MAIN__’ IN PYTHON # harry is a good boy
try: ‘__name__’ evaluates to the name of the module in python from where the program is
# output for 2:
# Code which might throw exception ran.
# boy is a good harry
except Exception as e:
print(e) If the module is being run directly from the command line, the ‘ __name__’ is set to
When the exception is handled, the code flow continues without program interruption. string “__main__”. Thus, this behaviour is used to check whether the module is run MAP, FILTER & REDUCE
directly or imported to another file.
Map applies a function to all the items in an input_list.
We can also specify the exception to catch like below:
THE GLOBAL KEYWORD Syntax.
try:
# Code ‘global’ keyword is used to modify the variable outside of the current scope. map(function, input_list)
except ZeroDivisionError:
# the function can be lambda function
# Code ENUMERATE FUNCTION IN PYTHON
except TypeError: Filter creates a list of items for which the function returns true.
# Code The ‘enumerate’ function adds counter to an iterable and returns it
except: list(filter(function))
# Code # All other exceptions are handled here. for i,item in list1: # the function can be lambda function
print(i,item) # Prints the items of list 1 with index Reduce applies a rolling computation to sequential pair of elements.
RAISING EXCEPTIONS
LIST COMPREHENSIONS from functools import reduce
We can raise custom exceptions using the ‘raise’ keyword in python.
val=reduce (function, list1)
List Comprehension is an elegant way to create lists based on existing lists.
# the function can be lambda function
TRY WITH ELSE CLAUSE
list1 = [1,7,12,11,22,]
Sometimes we want to run a piece of code when try was successful. list2 = [i for item in list 1 if item > 8]
50 51 54 55
CHAPTER 12 – ADVANCED PYTHON 1 The syntax of types looks something like this: CHAPTER 12 – PRACTICE SET CHAPTER 13 – ADVANCED PYTHON 2
NEWLY ADDED FEATURES IN PYTHON 1. Write a program to open three files 1.txt, 2.txt and 3.txt if any these files are not VIRTUAL ENVIRIONMENT
from typing import List, Tuple, Dict, Union
present, a message without exiting the program must be printed prompting the same.
Following are some of the newly added features in Python programming language An environment which is same as the system interpreter but is isolated from the other
# List of integers 2. Write a program to print third, fifth and seventh element from a list using enumerate Python environments on the system.
numbers: List[int] = [1, 2, 3, 4, 5]
WALRUS OPERATOR function.
The walrus operator (:=), introduced in Python 3.8, allows you to assign values to # Tuple of a string and an integer INSTALLATION
3. Write a list comprehension to print a list which contains the multiplication table of a
person: Tuple[str, int] = ("Alice", 30)
variables as part of an expression. This operator, named for its resemblance to the eyes user entered number. To use virtual environments, we write:
and tusks of a walrus, is officially called the "assignment expression." # Dictionary with string keys and integer values
4. Write a program to display a/b where a and b are integers. If b=0, display infinite by pip install virtualenv # Install the package
scores: Dict[str, int] = {"Alice": 90, "Bob": 85}
handling the ‘ZeroDivisionError’.
# Using walrus operator We create a new environment using:
# Union type for variables that can hold multiple types
if (n := len([1, 2, 3, 4, 5])) > 3: 5. Store the multiplication tables generated in problem 3 in a file named Tables.txt.
identifier: Union[int, str] = "ID123" virtualenv myprojectenv # Creates a new venv
print(f"List is too long ({n} elements, expected <= 3)")
identifier = 12345 # Also valid
The next step after creating the virtual environment is to activate it.
# Output: List is too long (5 elements, expected <= 3) These annotations help in making the code self-documenting and allow developers to
understand the data structures used at a glance. We can now use this virtual environment as a separate Python installation.
In this example, n is assigned the value of len([1, 2, 3, 4, 5]) and then used in
the comparison within the if statement.
MATCH CASE PIP FREEZE COMMAND
TYPES DEFINITIONS IN PYTHON Python 3.10 introduced the match statement, which is similar to the switch statement ‘pip freeze’ returns all the package installed in a given python environment along with
Type hints are added using the colon (:) syntax for variables and the -> syntax for found in other programming languages. the versions.
function return types. The basic syntax of the match statement involves matching a variable against several pip freeze > requirements .txt
cases using the case keyword. The above command creates a file named ‘requirements.txt’ in the same directory
# Variable type hint containing the output of ‘pip freeze’.
def http_status(status):
age: int = 25
match status: We can distribute this file to other users, and they can recreate the same environment
case 200:
# Function type hints using:
return "OK"
def greeting(name: str) -> str:
case 404:
return f"Hello, {name}!" pip install –r requirements.txt
return "Not Found"
case 500:
# Usage LAMBDA FUNCTIONS
return "Internal Server Error"
print(greeting("Alice")) # Output: Hello, Alice!
case _: Function created using an expression using ‘lambda’ keyword.
return "Unknown status"
ADVANCED TYPE HINTS Syntax:
# Usage
Python's typing module provides more advanced type hints, such as List, Tuple, Dict, print(http_status(200)) # Output: OK lambda arguments:expressions
and Union. print(http_status(404)) # Output: Not Found
print(http_status(500)) # Output: Internal Server Error # can be used as a normal function
You can import List, Tuple and Dict types from the typing module like this: print(http_status(403)) # Output: Unknown status Example:
from typing import List, Tuple, Dict, Union square = lambda x:x*x
DICTIONARY MERGE & UPDATE OPERATORS
square(6) # returns 36
New operators | and |= allow for merging and updating dictionaries. sum = lambda a,b,c:a+b+c
48 49 52 53
13. Processes commands to determine actions such as opening a website, playing MEGA PROJECT 2: AUTO-REPLY AI CHATBOT
music, fetching news, or generating a response via OpenAI.
DESCRIPTION
LIBRARIES USED
This project automates the process of interacting with a chat application, specifically
• speech_recognition designed to analyze chat history and generate humorous responses using OpenAI's
• webbrowser GPT-3.5-turbo model. The virtual assistant, named Naruto, is a character that roasts
• pyttsx3 people in a funny way, based on the chat history.
• musicLibrary
• requests FEATURES
• openai
14. Automated Chat Interaction
• gTTS 15. Uses pyautogui to perform mouse and keyboard operations, interacting with the
• pygame chat application without manual intervention.
• os 16. Chat History Analysis
17. 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").
18. Humorous Response Generation
19. Integrates with OpenAI's GPT-3.5-turbo model to generate funny, roast-style
responses based on the analyzed chat history.
20. Clipboard Operations
21. Utilizes pyperclip to copy and paste text, facilitating the retrieval and insertion of
chat messages.
22. Uses pyautogui to perform mouse and keyboard operations, interacting with the
chat application without manual intervention.
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
58 59
CHAPTER 13- PRACTICE SET MEGA PROJECT 1: JARVIS - VOICE-ACTIVATED VIRTUAL ASSISTANT • Analyze the copied chat history to check if the last message is from a specific
user (e.g., "Rohan Das").
1. Create two virtual environments, install few packages in the first one. How do you Jarvis is a voice-activated virtual assistant designed to perform tasks such as web • If the last message is from the target user, send the chat history to OpenAI's
create a similar environment in the second one? browsing, playing music, fetching news, and responding to user queries using OpenAI's GPT-3.5-turbo to generate a humorous response.
GPT-3.5-turbo model. • Copy the generated response to the clipboard.
2. Write a program to input name, marks and phone number of a student and format it
using the format function like below: • Send Response
FEATURES
• Click on the chat input area and paste the generated response.
“The name of the student is Harry, his marks are 72 and phone number is 99999888” • Voice Recognition • Press 'Enter' to send the response.
3. A list contains the multiplication table of 7. write a program to convert it to vertical • Utilizes the speech_recognition library to listen for and recognize voice commands. • Wait for a brief period to ensure the application is open and ready for interaction.
string of same numbers. • Activates upon detecting the wake word "Jarvis." • Chat History Retrieval
• Text-to-Speech • Retrieve the copied text from the clipboard.
• Converts text to speech using pyttsx3 for local conversion. • Message Analysis
• Uses gTTS (Google Text-to-Speech) and pygame for playback. • Analyze the copied chat history to check if the last message is from a specific
• Web Browsing. user (e.g., "Rohan Das").
• Opens websites like Google, Facebook, YouTube, and LinkedIn based on voice • Generate Response
commands. • Copy the generated response to the clipboard.
• Music Playback • Send Response
4. Write a program to filter a list of numbers which are divisible by 5.
• Interfaces with a musicLibrary module to play songs via web links.
5. Write a program to find the maximum of the numbers in a list using the reduce • News Fetching LIBRARIES USED
function. • Fetches and reads the latest news headlines using NewsAPI. 1. pyautogui: For automating mouse and keyboard interactions.
• OpenAI Integration 2. time: For adding delays between operations.
6. Run pip freeze for the system interpreter. Take the contents and create a similar
• Handles complex queries and generates responses using OpenAI's GPT-3.5-turbo. 3. pyperclip: For clipboard operations.
virtualenv.
• Acts as a general virtual assistant similar to Alexa or Google Assistant. 4. openai: For interacting with OpenAI's GPT-3.5-turbo model.
7. Explore the ‘Flask’ module and create a web server using Flask & Python. • 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."
56 57 60