The Ultimate Python Handbook22
The Ultimate Python Handbook22
PREFACE
This handbook aims to make programming accessible and enjoyable for everyone. Whether
you're a student new to coding, a professional seeking to enhance your skills, or an
enthusiast exploring Python, this handbook will definitely be helpful. Python's simplicity and
readability make it an ideal starting point for anyone interested in programming.
The handbook is divided into clear, concise chapters, each focused on a specific aspect of
Python:
● Fundamental Concepts: Start with the basics, such as installing Python and writing
your first program.
● Practical Examples: Illustrative examples and sample code demonstrate
the application of concepts.
● Hands-On Exercises: End-of-chapter exercises reinforce learning and build confidence.
WHY PYTHON?
Python is known for its simplicity and readability, making it perfect for beginners. It is a
high- level, interpreted language with a broad range of libraries and frameworks, supporting
applications in web development, data analysis, AI, and more. Python's versatility and ease
of use make it a valuable tool for both novice and experienced programmers.
ACKNOWLEDGEMENTS
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
students watching my content on YouTube and Python community for maintaining a
supportive and inspiring environment for learners worldwide.
CONCLUSION
Learning programming can be both exciting and challenging. The “Ultimate Python
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 success in the world of programming.
CONTENTS
PREFACE....................................................................................................................................1
Purpose and Audience..............................................................................................................1
Structure and Content..............................................................................................................1
Why Python?...........................................................................................................................1
Acknowledgements..................................................................................................................1
Conclusion...............................................................................................................................1
Contents.................................................................................................................................2
Python programming Handbook....................................................................................................6
What is Programming?.............................................................................................................6
What is Python?.......................................................................................................................6
Features of Python...................................................................................................................6
Installation..............................................................................................................................6
Chapter 1 – Modules, Comments C pip..........................................................................................7
Modules.................................................................................................................................. 7
pip..........................................................................................................................................7
Types of Modules.....................................................................................................................7
Using python as a calculator.....................................................................................................7
Comments...............................................................................................................................7
Types of Comments.................................................................................................................7
Chapter 1 – Practice Set...............................................................................................................9
Chapter 2 – Variables and Datatype............................................................................................10
Data Types............................................................................................................................10
Rules for choosing an identifier................................................................................................10
Operators in Python................................................................................................................10
type() function and typecasting...............................................................................................11
input() Function.....................................................................................................................11
Chapter 2 – Practice Set.............................................................................................................12
Chapter 3 – Strings....................................................................................................................13
String Slicing..........................................................................................................................13
Slicing With Skip Value............................................................................................................14
String Functions.....................................................................................................................14
Escape Sequence Characters...................................................................................................15
Chapter 3 – Practice Set.............................................................................................................16
Chapter 4 – Lists And Tuples......................................................................................................17
List Indexing..........................................................................................................................17
List methods..........................................................................................................................17
Tuples in Python....................................................................................................................17
Tuple Methods.......................................................................................................................17
Chapter 4 - Practice Set.............................................................................................................19
Chapter 5 – Dictionary C Sets.....................................................................................................20
Properties of Python Dictionaries.............................................................................................20
Dictionary Methods.................................................................................................................20
Sets in Python........................................................................................................................20
Properties of Sets...................................................................................................................21
Operations on sets.................................................................................................................21
Chapter 5 – Practice Set.............................................................................................................22
Chapter 6 – Conditional Expression.............................................................................................23
If Else and Elif in Python.........................................................................................................23
Code example........................................................................................................................23
Relational Operators...............................................................................................................24
Logical Operators...................................................................................................................24
Elif clause..............................................................................................................................24
Important notes.....................................................................................................................24
Chapter 6 – Practice Set.............................................................................................................25
Chapter 7 – Loops in Python.......................................................................................................26
Types of Loops in Python........................................................................................................26
While loop.............................................................................................................................26
For loop.................................................................................................................................27
range() Function in Python......................................................................................................27
An Example Demonstrating range() function.............................................................................27
For Loop with Else..................................................................................................................27
The Break Statement..............................................................................................................27
The Continue Statement.........................................................................................................28
Pass statement......................................................................................................................28
Chapter 7 – Practice Set.............................................................................................................29
Chapter 8 – Functions C Recursions............................................................................................30
Example and syntax of a function............................................................................................30
Function call..........................................................................................................................30
Function Definition.................................................................................................................30
Types of Functions in Python...................................................................................................30
Functions with Arguments.......................................................................................................30
Default Parameter Value.........................................................................................................31
Recursion..............................................................................................................................31
Chapter 8 – Practice Set.............................................................................................................33
Project 1: Snake, Water, Gun Game............................................................................................34
Chapter 9 – File I/O...................................................................................................................35
Type of Files..........................................................................................................................35
Opening a File........................................................................................................................35
Reading a File in Python.........................................................................................................35
Other methods to read the file.................................................................................................36
Modes of opening a file...........................................................................................................36
Write Files in Python...............................................................................................................36
With Statement......................................................................................................................36
Chapter 9 – Practice Set.............................................................................................................37
Chapter 10 - Object Oriented Programming.................................................................................38
Class.....................................................................................................................................38
Object...................................................................................................................................38
Modelling a problem in OOPs...................................................................................................38
Class Attributes......................................................................................................................38
Instance attributes.................................................................................................................39
self parameter........................................................................................................................39
static method.........................................................................................................................39
init () constructor..................................................................................................................40
Chapter 10 – Practice Set...........................................................................................................41
Chapter 11 - Inheritance C more on OOPs...................................................................................42
Types of Inheritance...............................................................................................................42
Single Inheritance..................................................................................................................42
Multiple Inheritance................................................................................................................43
Multilevel Inheritance.............................................................................................................43
super() method......................................................................................................................43
class method..........................................................................................................................44
@property Decorators.............................................................................................................44
@.getters and @.setters.........................................................................................................44
Operator Overloading in Python...............................................................................................44
Chapter 11- Practice set.............................................................................................................46
Project 2 – The Perfect Guess.....................................................................................................47
Chapter 12 – Advanced Python 1................................................................................................48
Newly added features in python..............................................................................................48
Walrus Operator.....................................................................................................................48
Types Definitions in Python.....................................................................................................48
Advanced Type Hints..............................................................................................................48
Match Case............................................................................................................................49
Dictionary Merge C Update Operators......................................................................................49
Exception handling in Python...................................................................................................50
Raising Exceptions..................................................................................................................50
try with else clause.................................................................................................................50
try with finally........................................................................................................................51
If name == ‘ main ’ in python...................................................................................................................51
The global keyword................................................................................................................51
enumerate function in python..................................................................................................51
List comprehensions...............................................................................................................51
Chapter 12 – Practice set...........................................................................................................52
Chapter 13 – Advanced Python 2................................................................................................53
Virtual environment................................................................................................................53
Installation............................................................................................................................53
pip freeze command...............................................................................................................53
Lambda functions...................................................................................................................53
join method (strings)..............................................................................................................54
format method (strings)..........................................................................................................54
Map, Filter C Reduce...............................................................................................................54
Chapter 13 – Practice Set...........................................................................................................56
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
PYTHON PROGRAMMING HANDBOOK
WHAT IS PROGRAMMING?
Just like we use Bengali or English to communicate with each other, we use a
programming language like Python to communicate with the computer.
WHAT IS PYTHON?
Python is a simple and easy to understand language which feels like reading simple
English. This pseudo code nature is easy to learn and understandable by beginners.
FEATURES OF PYTHON
INSTALLATION
Python can be easily installed from [Link]. When you click on the download
button, python can be installed right after you complete the setup by executing the
file for your platform.
CHAPTER 1 – MODULES, COMMENTS & PIP
Let’s write our very first python program. Create a file called [Link] and write
the below code in it.
Execute this file (.py file) by typing python [Link] and you will see Hello World
printed on the screen.
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.
pip install flask # Installs Flask Module
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.
1. Single Line Comments: To write a single line comment just add a ‘#’ at the
start of the line.
# This is a Single-Line Comment
2. Multiline Comments: To write multi-line comments you can use ‘#’ at each line
or you can use the multiline string (""" """)
"""This is an amazing
example of a
Multiline comment!"""
CHAPTER 1 – PRACTICE SET
1. Write a program to print Twinkle twinkle little star poem in python.
2. Use REPL and print the table of 5 using it.
3. Install an external module and use it to perform an operation of your interest.
4. Write a python program to print the contents of a directory using the os
module. Search online for the function which does that.
5. Label the program written in problem 4 with comments.
CHAPTER 2 – VARIABLES AND DATATYPE
DATA TYPES
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.
a= 71 # identifies a as class
b=88.4 <int>
4
name= "harry"# #identifies
identifiesb name
as class
as class
<str>
RULES FOR CHOOSING AN IDENTIFIER
Examples of a few variable names are: harry, one8, seven, _seven etc.
Following are some common operators in python:
a = 31
type(a) # class <int>
b = "31"
type (b) # class <str>
into another.
INPUT () FUNCTION
This function allows the user to take input from the keyboard as a string.
The index in a string 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).
SLICING WITH SKIP VALUE
We can provide a skip value as a part of our slice like this:
word = "amazing"
word[1: 6: 2] # "mzn"
Word = "amazing"
Word = [:7] # word [0:7] – 'amazing'
Word = [0:] # word [0:7] – 'amazing'
STRING FUNCTIONS
Some of the commonly used functions to perform operations on or manipulate strings
are as follows. Let us assume there is a string ‘str’ as follows:
str = 'harry'
Now when operated on this string ‘str’, these functions do the following:
str = "harry"
print(len(str)) # Output:
5
2. [Link]("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.
str = "harry"
print([Link]("rry")) # Output: True
3. [Link]("c") – counts the total number of occurrences of any character.
str = "harry"
count = [Link]("r")
print(count) # Output: 2
4. the first character of a given string.
str = "harry"
capitalized_string = [Link]()
print(capitalized_string) # Output: "Harry"
str = "harry"
index = [Link]("rr")
print(index) # Output: 2
6. [Link] (old word, new word ) – This function replace the old word
with new word in the entire string.
str = "harry"
replaced_string = [Link]("r", "l")
print(replaced_string) # Output: "hally"
Escape Sequence characters consist of more than one character but represent one
character when used within the strings.
CHAPTER 3 – PRACTICE SET
1. Write a python program to display a user entered name followed by
Good Afternoon using input () function.
2. Write a program to fill in a letter template given below with name and date.
letter = '''
Dear <|
Name|>, You are
selected!
<
|Date|
3. Write a program to detect double space in a string.
4. Replace the double space from problem 3 with single spaces.
5. Write a program to format the following letter using escape
sequence characters.
letter = "Dear Harry, this python course is nice. Thanks!"
CHAPTER 4 – LISTS AND TUPLES
Python lists are containers to store a set of values of any data type.
LIST INDEXING
l1 = [7,9,"harry"]
l1[0] # 7
l1[1] # 9
l1[70] # error
l1[0:2] # [7,9] #list slicing
LIST METHODS.
l1 = [1,8,7,2,21,15]
TUPLES IN PYTHON
TUPLE METHODS
Consider the following tuple.
a = (1, 7, 2)
● [Link] (1): a count (1) will return the number of times 1 occurs in a.
Syntax:
a = {
"key": "value",
"harry": "code",
"marks": "100",
"list": [1, 2, 9]
}
1. It is unordered.
2. It is mutable.
3. It is indexed.
4. Cannot contain duplicate keys.
DICTIONARY METHODS
a={"name":"harry"
"from":"india"
"marks":[92,98,96]}
SETS IN PYTHON.
s = # no repetition
set() allowed!
[Link](1) # or set
[Link](2) ={1,2}
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
unique values.
PROPERTIES OF SETS
1. Sets are unordered => Element’s order doesn’t matter
2. Sets are unindexed => Cannot access elements by index
3. There is no way to change items in sets.
4. Sets cannot contain duplicate values.
OPERATIONS ON SETS
Syntax:
if (condition1): # if condition1 is
True print ("yes")
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.
RELATIONAL OPERATORS
Relational Operators are used to evaluate conditions inside the if statements. Some
examples of relational operators are:
==: equals.
LOGICAL OPERATORS
In python logical operators operate on conditional statements. For Example:
ELIF CLAUSE
elif in python means [else if]. An if statements can be chained together with a
lot of these elif statements followed by an else statement.
if
(condition1):
#code
elif (condition2): # this ladder will stop once a condition in
an if or elif is met.
#code
elif(condition3):
#cod
e 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.
CHAPTER 6 – PRACTICE SET
1. Write a program to find the greatest of four numbers entered by the user.
2. Write a program to find out whether a student has passed or failed if it
requires a total of 40% and at least 33% in each subject to pass. Assume 3
subjects and take marks as an input from the user.
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 to detect these spams.
4. Write a program to find whether a given username contains less than
10 characters or not.
5. Write a program which finds out whether a given name is present in a list or
not.
6. Write a program to calculate the grade of a student from his marks from
the following scheme:
90 – 100 => Ex
80 – 90 => A
70 – 80 => B
60 – 70 =>C
50 – 60 => D
<50 => F
7. Write a program to find out whether a given post is talking about “Harry” or
not.
CHAPTER 7 – LOOPS IN PYTHON
Sometimes we want to repeat a set of statements in our program. For instance:
Print 1 to 1000.
Loops make it easy for a programmer to tell the computer which set of instructions
to repeat and how!
● while loops
● for loops
WHILE LOOP
Syntax:
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.
FOR LOOP
A for loop is used to iterate through a sequence like list, tuple, or string [iterables]
Syntax:
l = [1, 7, 8]
for item in l:
print(item) # prints 1, 7 and 8
number. We can also specify the start, stop and step-size as follows:
print(i) # prints 0 to 6
Example:
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
for i in range
(0,80):
print(i) # this will print 0,1,2
if i==3 and 3
b
reak
THE CONTINUE STATEMENT
‘continue’is used to stop the current iteration of the loop and continue with the
next one. It instructs the Program to “skip this iteration”.
Example:
for i in range(4):
print("printing")
if i == 2: # if i is 2, the
iteration is skipped continue
print(i)
PASS STATEMENT
nothing”.
Example:
l = [1,7,8]
for item
in l: # without pass, the program will throw an
pass error
CHAPTER 7 – PRACTICE SET
1. Write a program to print multiplication table of a given number using for loop.
2. Write a program to greet all the person names stored in a list ‘l’ and which
starts with S.
l = ["Harry", "Soham", "Sachin", "Rahul"]
3. Attempt problem 1 using while loop.
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.
6. Write a program to calculate the factorial of a given number using for loop.
7. Write a program to print the following star pattern.
*
***
***** for n = 3
8. Write a program to print the following star pattern:
*
**
*** for n = 3
9. Write a program to print the following star pattern.
***
* * for n = 3
***
[Link] a program to print multiplication table of n using for loops in
reversed order.
CHAPTER 8 – FUNCTIONS C RECURSIONS
When a program gets bigger in size and its complexity grows, it gets difficult for a
program to keep track on which piece of code is doing what!
def func1():
print('hello')
This function can be called any number of times, anywhere in the program.
FUNCTION CALL
The part containing the exact set of instructions which are executed during the
function call.
Quick Quiz: Write a program to greet a user with “Good day” using functions.
A function can accept some value it can work with. We can put these values in the
parentheses.
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:
def greet(name =
"stranger"): # function
body
greet() # name will be "stranger" in function body (default)
greet("harry") # name will be "harry" in function body (passed)
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
This works as follows:
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.
A file is data stored in a storage device. A python program can talk to the file by
reading content from it and writing content to it.
TYPE OF FILES.
OPENING A FILE
Python has an open() function for opening files. It takes 2 parameters: filename
and mode.
We can also use [Link]() function to read one full line at a time.
r – open for
reading w - open
for writing
WITH STATEMENT
The best way to open and close the file automatically is the with statement.
Synta
x:
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 C Encapsulation!
CLASS ATTRIBUTES
An attribute that belongs to the Instance (object). Assuming the class from the
previous example:
[Link] = "harry"
[Link] = "30k" # Adding instance attribute
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):
STATIC METHOD
Sometimes we need a function that does not use the self-parameter. We can define
a static method like this:
init () is a special method which is first run as soon as the object is created.
For Example:
class Employee:
def init (self, name):
[Link]=name
def getSalary(self):
...
harry = Employee("Harry")
CHAPTER 10 – PRACTICE SET
1. Create a class “Programmer” for storing information of few
programmers working at Microsoft.
2. Write a class “Calculator” capable of finding square, cube and square root
of a number.
3. Create a class with a class attribute a; create an object from it and set ‘a’
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.
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.
6. Can you change the self-parameter inside a class to something else (say
“harry”). Try changing self to “slf” or “harry” and see the effects.
CHAPTER 11 - INHERITANCE C MORE ON OOPS
Inheritance is a way of creating a new class from an existing class.
Syntax:
class.
TYPES OF INHERITANCE
● Single inheritance
● Multiple inheritance
● Multilevel inheritance
SINGLE INHERITANCE
Single inheritance occurs when child class inherits only a single parent class.
MULTIPLE INHERITANCE
Multiple Inheritance occurs when the child class inherits from more than one parent
classes.
MULTILEVEL INHERITANCE
When a child class becomes a parent for another child class.
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
CLASS METHOD
A class method is a method which is bound to the class and not the object of the
class.
Syntax:
@classmethod
@PROPERTY DECORATORS
def(cls,p1,p2):
class
If e = Employee() is an object of class employee, we can print ([Link]) to print the
Employee:
ename by internally calling name() function.
@property
def
name(self):
below:
@[Link]
def name (self,value):
[Link] = value
These methods are called when a given operator is used on the objects.
p1+p2dunder/magic
Other # p1. add (p2)
methods in Python:
p1-p2 # p1. sub (p2)
p1*p2 # p1. mul (p2)
p1/p2 # p1. truediv (p2)
p1//p2 # p1. floordiv
(p2)
len () # used to set what gets displayed upon calling. len () or
len(obj)
CHAPTER 11- PRACTICE SET
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
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
number please” When the user guesses the correct number, the program displays
the number of guesses the player used to arrive at the number.
Following are some of the newly added features in Python programming language
WALRUS OPERATOR
The walrus operator (:=), introduced in Python 3.8, allows you to assign values to
variables as part of an expression. This operator, named for its resemblance to the
eyes 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:
MATCH CASE
Python 3.10 introduced the match statement, which is similar to the switch
statement found in other programming languages.
The basic syntax of the match statement involves matching a variable against
several cases using the case keyword.
def
http_status(status):
match status:
case 200:
retur
n "OK" case 404:
return
"Not Found" case
500:
return "Internal
Server Error" case _:
return "Unknown status"
# Usage
print(http_status(200)) # Output: OK
print(http_status(404)) # Output: Not Found
print(http_status(500)) # Output: Internal Server
Error print(http_status(403)) # Output: Unknown status
DICTIONARY MERGE C UPDATE OPERATORS
with (
open('[Link]') as f1,
open('[Link]') as f2
):
# Process files
Exception in python can be handled using a try statement. The code that handles
the exception is written in the except clause.
try:
# Code which might throw exception
except Exception as e:
print(e)
When the exception is handled, the code flow continues without program
try:
# Code
except
ZeroDivisionError:
# Code
except
TypeError: #
Code
# # All other exceptions are handled
Code here.
RAISING EXCEPTIONS
We can raise custom exceptions using the ‘raise’ keyword in python.
try:
# Some
Code except:
# Some
Code finally:
# Some # Executed regardless of
Code error!
IF NAME == ‘ MAIN ’ IN PYTHON
‘ name ’ evaluates to the name of the module in python from where the program is
ran.
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]
CHAPTER 12 – PRACTICE SET
1. Write a program to open three files [Link], [Link] and [Link] if any these files are not
present, a message without exiting the program must be printed prompting the
same.
2. Write a program to print third, fifth and seventh element from a list using
enumerate function.
3. Write a list comprehension to print a list which contains the multiplication table
of a user entered number.
4. Write a program to display a/b where a and b are integers. If b=0, display
infinite by handling the ‘ZeroDivisionError’.
VIRTUAL ENVIRIONMENT
An environment which is same as the system interpreter but is isolated from the
other Python environments on the system.
INSTALLATION
We can distribute this file to other users, and they can recreate the same
environment using:
LAMBDA FUNCTIONS
Function created using an expression using ‘lambda’ keyword.
Syntax:
lambda arguments:expressions
Example:
[Link](p1,p2...)
Syntax:
# output for 1:
# harry is a good boy
# output for 2:
# boy is a good harry
Syntax.
map(function, input_list)
# the function can be lambda function
Filter creates a list of items for which the function returns true.
list(filter(function))
# the function can be lambda function
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 C Python.
MEGA PROJECT 1: JARVIS - VOICE-ACTIVATED VIRTUAL ASSISTANT
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 GPT-3.5-turbo model.
FEATURES
● Voice Recognition
● Utilizes the speech_recognition library to listen for and recognize voice commands.
● Text-to-Speech
● Web Browsing.
● News Fetching
● OpenAI Integration
● 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.
[Link] the user with "Initializing Jarvis."
[Link] Word Detection
[Link] activation by saying "Ya."
[Link] commands to determine actions such as opening a website,
playing music, fetching news, or generating a response via OpenAI.
LIBRARIES USED
● speech_recognition
● webbrowser
● pyttsx3
● musicLibrary
● requests
● openai
● gTTS
● pygame
● os
MEGA PROJECT 2: AUTO-REPLY AI CHATBOT
DESCRIPTION
This project automates the process of interacting with a chat application,
specifically designed to analyze chat history and generate humorous responses
using OpenAI's GPT-3.5-turbo model. The virtual assistant, named Naruto, is a
character that roasts people in a funny way, based on the chat history.
WORKFLOW
● Initialization and Setup
● 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
● Analyze the copied chat history to check if the last message is from a
specific user (e.g., "Rohan Das").
● 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.
● Copy the generated response to the clipboard.
● Send Response
● Click on the chat input area and paste the generated response.
● Wait for a brief period to ensure the application is open and ready for
interaction.
● Chat History Retrieval
● Message Analysis
● Analyze the copied chat history to check if the last message is from a
specific user (e.g., "Rohan Das").
● Generate Response
● Send Response
LIBRARIES USED
1. pyautogui: For automating mouse and keyboard interactions.
2. time: For adding delays between operations.
3. pyperclip: For clipboard operations.
4. openai: For interacting with OpenAI's GPT-3.5-turbo model.