Python Tutorial Notes
Python Tutorial Notes
Introduction Of Python:
Python is a simple, general purpose, high level, and object-
oriented programming language.
Python is an interpreted scripting language also. Guido Van
Rossum is known as the founder of
Python programming.
What is Python
Python is a general purpose, dynamic, high-level, and interpreted
programming language. It
supports Object Oriented programming approach to develop
applications. It is simple and easy to
learn and provides lots of high-level data structures.
Python History
Python was invented by Guido van Rossum in 1991 at CWI in
Netherland. The idea of Python predecessor
programming language has taken from the ABC programming
language or we can say that ABC is a
of Python language.
There is also a fact behind the choosing name Python. Guido van
Rossum was a fan of the popular BBC
comedy show of that time, "Monty Python's Flying Circus". So
Python tutorial
he decided to pick the name Python for
his newly created programming language.
Python has the vast community across the world and releases its
version within the short period.
o Expressive Language
o Interpreted Language
o Object-Oriented Language
o Extensible
o Integrated
o Embeddable
o Date Mining
o Desktop Applications
o Console-based Applications
o Mobile Applications
o Software Development
o Artificial Intelligence
o Machine Learning
o Web Applications
o 3D CAD Applications
o Enterprise Applications
o Speech Recognitions
What is pip?
Python pip is the package manager for Python packages. We can
use pip to install packages that do not
come with Python. The basic syntax of pip commands in command
prompt is:
pip 'arguments'
Python Applications
Python is known for its general-purpose nature that makes it
applicable in almost every domain of
software development. Python makes its presence in every
emerging field. It is the fastest-growing
programming language and can develop any application.
Here, we are specifying application areas where Python can be
applied.
Python tutorial
Comment in python:
There are two types of Comments are available in Python:
1. Single Line Comments : We use # for Single line comment in
Python.
2. Multi Line Comments : We use “““Triple court””” for multi line
comment in Python.
Example:
#This is the single line comment
print("Hello friends! My name is Harion Singh Rajput", end=" and ")
"""
This
is
The
Multi
Line
Python tutorial
Comment
"""
print("This information is all about comments in python")
Output:
Hello friends! My name is Harion Singh Rajput and This information
is all about comments in
python
Use of end=“ ” :-
By default python’s print() function ends with a
newline. Python’s print() function comes
with a parameter called ‘end’. By default, the value of this
parameter is ‘\n’, i.e. the new line character.
You can end a print statement with any character/string using this
parameter, as you can see in above
example.
Python Keywords:
Python Keywords are special reserved words that convey a special
meaning to the compiler/interpreter.
Each keyword has a special meaning and a specific operation.
These keywords can't be used as a
variable.
Following is the List of Python Keywords.
True False None and as
a2 = eval(input("Enter a2 : "))
b2 = eval(input("Enter b2 : "))
a3 = eval(input("Enter a3 : "))
b3 = eval(input("Enter b3 : "))
Python Operators
The operator can be defined as a symbol which is responsible for a
particular operation between two operands. Operators are the
pillars of a program on which the logic is built in a specific
programming language. Python provides a variety of operators,
which are described as follows.
o Arithmetic operators
o Comparison operators
o Assignment Operators
o Logical Operators
o Bitwise Operators
o Membership Operators
o Identity Operators
Arithmetic Operators
Python tutorial
Operator Description
Comparison operator
Oper Description
ator
Assignment Operators
The assignment operators are used to assign the value of the right
expression to the left operand. The assignment operators are
Python tutorial
Oper Description
ator
Bitwise Operators
For example,
if a = 7
b = 6
then, binary (a) = 0111
binary (b) = 0110
Operat Description
or
# print(0 & 2)
# print(1 | 3)
a=3
b=5
print(a & b)
print(a | b)
print(~(a | b))
print(a ^ b)
print(a << b)
print(a >> b)
Output:
1
7
-8
6
96
Python tutorial
0
Logical Operators
Oper Description
ator
and If both the expression are true, then the condition will
be true. If a and b are the two expressions, a → true,
b → true => a and b → true.
or If one of the expressions is true, then the condition
will be true. If a and b are the two expressions, a →
true, b → false => a or b → true.
not If an expression a is true, then not (a) will be false
and vice versa.
Example:
a = True
b = False
print(a and b)
print(a or b)
print(not (a and b))
print(not (a or b))
Output:
False
True
True
False
Python tutorial
Membership Operators
Oper Description
ator
Identity Operators
Python tutorial
Oper Description
ator
Output:
a = 10
b = 11
a is b = False
a is not b = True
Operator Precedence
The precedence of the operators is essential to find out since it
enables us to know which operator should be evaluated first. The
precedence table of the operators in Python is given below.
Python tutorial
Operator Description
Literals in Python
Generally, literals are a notation for representing a fixed value in
Python tutorial
source code. They can also be defined as raw value or data given
in variables or constants.
Example:
# Numeric literals
x = 24
y = 24.3
z = 2+3j
print(x, y, z)
Output
24 24.3 (2+3j)
1. String literals:
"Aman" , '12345'
Types of Strings:
Python tutorial
# Single-line String
text1 = 'hello' # By using single quotes
text2 = "Hariom mewada" # By using double quotes
print(text1)
print(text2)
Output:
hello
Hariom mewada
# Multi-line String
str1 = """hariom
singh
rajput"""
hariom
Python tutorial
singh
rajput
My name is
Hariom Mewada
# Float Literal
float_1 = 100.5
float_2 = 1.5e2
Python tutorial
# Complex Literal
a = 5 + 3.14j
print(x, y, z, u)
print(float_1, float_2)
print(a, a.imag, a.real)
Output:
A Boolean literal can have any of the two values: True or False.
x = (1 == True)
y = (2 == False)
z = (3 == True)
a = True + 10
b = False + 10
print("x is", x)
print("y is", y)
print("z is", z)
print("a:", a)
print("b:", b)
Output:
False
z is False x is True
y is
a: 11
Python tutorial
b: 10
val1=10
val2=None
print(val1)
print(val2)
Output:
10
None
V. Literal Collections.
List:
list=['John',678,20.4,'Peter']
list1=[456,'Andrew']
print(list)
Python tutorial
print(list + list1)
Output:
Dictionary:
Tuple:
tup = (10,20,"Dev",[2,3,4])
print(tup)
Output:
Set:
Python tutorial
o Python set is the collection of the unordered dataset.
o It is enclosed by the {} and each element is separated by the
comma(,).
set = {'apple','grapes','guava','papaya'}
print(set)
Output:
Python Variables
Variable is a name that is used to refer to memory location. Python
variable is also known as an identifier and used to hold value.
Identifier Naming
print(var2+var3)
print(str(var2)+str(var3)) #Typecast var2 and var3 into string
print(var1+var4)
a = "55" #Here a is a string not an integer
b = "45" #Like a, b is also an string here
print(a+b) #It will concatinate a and b because a and b are
strings
print(int(a)+int(b)) #Typecasting of a and b in integer
print(10*"Hello, My Name is Hariom Singh Rajput \n") #Print
given string 10 times
Output:
94.5
4549.5
5545
100
Object References
print(type(var1))
print(type(var2))
print(type(var3))
Output:
Python tutorial
<class 'str'>
<class 'int'>
<class 'float'>
a= 5
b = 10
c = 15
Local Variable
Local variables are the variables that declared inside the function
and have scope within the function. Let's understand the following
example.
# Declaring a function
def add():
# Defining local variables. They has scope only within a function
a = 20
b = 30
Python tutorial
c=a+b
print("The sum is:", c)
# Calling a function
add()
Output:
Global Variables
mainFunction()
print(x)
Output:
101
print(l, "HSR")
# print(m) # This will throw an error because m is a local
variable
function1("Hariom")
Output:
Hello HSR
125
Example3:
def func1():
x = 20
def func2():
global x # this will make a global variable x with value 50
x = 50
Python tutorial
print("Before calling func2 x =", x)
func2()
print("After calling func2 x =", x)
func1()
print("value of global variable is:", x)
Output:
Delete a variable
We can delete the variable using the del keyword. The syntax is
given below.
Syntax -
del <variable_name>
a = 10000000000000000000000000000000000000000000
a=a+1
print(type(a))
print (a)
Output:
<class 'int'>
10000000000000000000000000000000000000000001
Python doesn't have any special data type to store larger numbers.
Python tutorial
Output:
95
Addition = 100
Subtraction = 90
Multiplication = 475
Division = 19.0
print(a == b)
print(a is b)
print(a == c)
print(a is c)
print(b == c)
print(b is c)
print()
x = [2, 4, 'xyz', 'abc', 78, 100]
y = [2, 4, 'xyz', 'abc', 78, 100]
print(x == y)
print(x is y)
Output:
True
True
True
False
True
False
True
False
Variables can hold values, and every value has a data-type. Python
is a dynamically typed language; hence we do not need to define
the type of the variable while declaring it. The interpreter implicitly
binds the value with its type.
a=5
Python enables us to check the type of the variable used in the
program. Python provides us the type() function, which returns
the type of the variable passed.
Example:
a=10
b="Hi Python"
c = 10.5
print(type(a))
print(type(b))
print(type(c))
Output:
<type 'int'>
<type 'str'>
<type 'float'>
Numbers
Number stores numeric values. The integer, float, and complex
values belong to a Python Numbers data-type. Python provides
the type() function to know the data-type of the variable.
Similarly, the isinstance() function is used to check an object
belongs to a particular class.
a=5
print("The type of a", type(a))
Python tutorial
b = 40.5
print("The type of b", type(b))
c = 1+3j
print("The type of c", type(c))
print(" c is a complex number", isinstance(1+3j,complex))
Output:
Boolean
Boolean type provides two built-in values, True and False. These
values are used to determine the given statement true or false. It
denotes by the class bool. True can be represented by any non-
zero value or 'T' whereas false can be represented by the 0 or 'F'.
Consider the following example.
Output:
<class 'bool'>
<class 'bool'>
NameError: name 'false' is not defined
Sequence Type
String
The string can be defined as the sequence of characters
represented in the quotation marks. In Python, we can use single,
double, or triple quotes to define a string.
Syntax:
below figure.
str = "HELLO"
print(str[0])
print(str[1])
print(str[2])
print(str[3])
print(str[4])
# It returns the IndexError because 6th index doesn't exist
print(str[6])
Output:
H
E
L
L
Python tutorial
O
IndexError: string index out of range
slicing in the string:
The slice operator [] is used to access the individual characters of
the string. However, we can use the : (colon) operator in Python to
access the substring from the given string.
#Slicing in string
Output:
Python tutorial
Hariom is a good boy
Lenght of mystr is: 20
H
a
r
i
o
m
y
good boy
Hro sago o
Hariom is a good boy
Hariom
Hariom is a good boy
Hariom is a good boy
Hariom is a good boy
Hi
Hariom is a good bo
yob doog a si moiraH
ybdo imia
String Operators
Operator Description
Example
str = "Hello"
str1 = " world"
print(str*3) # prints HelloHelloHello
print(str+str1)# prints Hello world
print(str[4]) # prints o
print(str[2:4]); # prints ll
Python tutorial
Output:
HelloHelloHello
Hello world
o
ll
False
False
C://python37
The string str : Hello
Example
print(str)
Output:
Example -
Output:
Example 1:
#Positional Argument
print("{1} and {0} best players ".format("Virat","Rohit"))
#Keyword Argument
print("{a},{b},{c}".format(a = "James", b = "Peter", c = "Ric
ky"))
Output:
Example 2:
Output:
(Integer,Float,String))
Output:
Function Description
Name
capitalize(Converts the first character of the string
) to a capital (uppercase) letter
casefold() Implements caseless string matching
center() Pad the string with the specified
character.
count() Returns the number of occurrences of a
substring in the string.
encode() Encodes strings with the specified
encoded scheme
endswith() Returns “True” if a string ends with the
given suffix
expandtab Specifies the amount of space to be
s() substituted with the “\t” symbol in the
string
find() Returns the lowest index of the substring
if it is found
format() Formats the string for printing it to
console
format_ma Formats specified values in a string using
p() a dictionary
Python tutorial
index() Returns the position of the first
occurrence of a substring in a string
isalnum() Checks whether all the characters in a
given string is alphanumeric or not
isalpha() Returns “True” if all characters in the
string are alphabets
isdecimal( Returns true if all characters in a string
) are decimal
isdigit() Returns “True” if all characters in the
string are digits
isidentifie Check whether a string is a valid identifier
r() or not
islower() Checks if all characters in the string are
lowercase
isnumeric( Returns “True” if all characters in the
) string are numeric characters
isprintable Returns “True” if all characters in the
() string are printable or the string is empty
isspace() Returns “True” if all characters in the
string are whitespace characters
istitle() Returns “True” if the string is a title cased
string
isupper() Checks if all characters in the string are
uppercase
join() Returns a concatenated String
ljust() Left aligns the string according to the
width specified
lower() Converts all uppercase characters in a
string into lowercase
lstrip() Returns the string with leading characters
removed
maketrans Returns a translation table
()
partition() Splits the string at the first occurrence of
the separator
Python tutorial
replace() Replaces all occurrences of a substring
with another substring
rfind() Returns the highest index of the substring
rindex() Returns the highest index of the substring
inside the string
rjust() Right aligns the string according to the
width specified
rpartition( Split the given string into three parts
)
rsplit() Split the string from the right by the
specified separator
rstrip() Removes trailing characters
splitlines() Split the lines at line boundaries
startswith Returns “True” if a string starts with the
() given prefix
strip() Returns the string with both leading and
trailing characters
swapcase( Converts all uppercase characters to
) lowercase and vice versa
title() Convert string to title case
translate() Modify string according to given
translation mappings
upper() Converts all lowercase characters in a
string into uppercase
zfill() Returns a copy of the string with ‘0’
characters padded to the left side of the
string
Example:
Output:
False
True
True
2
Hariom is a good boy
7
HARIOM IS A GOOD BOY
hariomisagoodboy
Example:
# chr function
number = int(input("Enter a number: "))
ASCII_char = chr(number)
print("This is the ASCII value of ", ASCII_char)
print(type(ASCII_char))
Output:
Enter a number: 67
<class 'str'>
Example:
# ord function
character = input("Enter a character: ")
ASCII_value = ord(character)
print("The ASCII value of this character is ", ASCII_value)
print(type(ASCII_value))
Output:
Enter a character: @
<class 'int'>
Python List
A list in Python is used to store the sequence of various types of data. Python lists are
mutable type its mean we can modify its element after it created. However, Python
consists of six data-types that are capable to store the sequences, but the most common
and reliable type is the list.
A list can be defined as a collection of values or items of different types. The items in the
list are separated with the comma (,) and enclosed with the square brackets [].
Example:
grocery = ["pen", "Rice", "Sugar", "Mixer", "Fan", "Eraser", 87]
print("Total list is: ", grocery)
print(grocery[1])
print(grocery[5])
# print(grocery[6]) #it will give an error
numbers = [65, 76, 98, 34, 9, 2, 4, 12]
print(numbers)
numbers[0] = 10
numbers[2] = 30
print(numbers)
Output:
Total list is: ['pen', 'Rice', 'Sugar', 'Mixer', 'Fan', 'Eraser', 87]
Rice
Eraser
[65, 76, 98, 34, 9, 2, 4, 12]
Characteristics of Lists
The list has the following characteristics:
Example:
a = [1, 2,"Peter", 4.50,"Ricky",5, 6]
b = [1, 2,"Peter", 4.50,"Ricky",5, 6]
a == b
Output:
Python tutorial
True
The index starts from 0 and goes to length - 1. The first element of the list is stored at
the 0th index, the second element of the list is stored at the 1st index, and so on.
Slicing in list:
We can get the sub-list of the list using the following syntax.
1. list_varible(start:stop:step)
Example:
numbers = [9, 3, 5, 2, 9, 12, 87, 54, 2, 54, 21]
print(numbers[0:11])
print(numbers[:11])
print(numbers[:])
print(numbers[2:])
print(numbers[::2])
print(numbers[::-1])
Output:
[9, 3, 5, 2, 9, 12, 87, 54, 2, 54, 21]
[9, 3, 5, 2, 9, 12, 87, 54, 2, 54, 21]
[9, 3, 5, 2, 9, 12, 87, 54, 2, 54, 21]
[5, 2, 9, 12, 87, 54, 2, 54, 21]
[9, 5, 9, 87, 2, 21]
The last element (rightmost) of the list has the index -1; its adjacent left element is
present at the index -2 and so on until the left-most elements are encountered.
Let's have a look at the following example where we will use negative indexing to access
the elements of the list.
1. list = [1,2,3,4,5]
2. print(list[-1])
3. print(list[-3:])
4. print(list[:-1])
5. print(list[-3:-1])
Output:
5
[3, 4, 5]
[1, 2, 3, 4]
[3, 4]
Python tutorial
l2 = []
# For a multiple string
for a in range(1, 6):
m = input("Enter sting " + str(a) + "--> ")
l2.append(m)
Output:
Enter a string: Wellcome to the python coarse
Your First List Is: ['Wellcome', 'to', 'the', 'python', 'coarse']
Enter sting 1--> Red
Enter sting 2--> Blue
Enter sting 3--> Green
Enter sting 4--> Yellow
Enter sting 5--> Pink
Example:
l = []
# Normal way to create a list by using for loop
print("Creating list by using for loop...")
for i in range(1, 11):
l.append(i)
print(l)
Output:
Creating list by using for loop...
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
t = len(l1)
for a in range(t):
print(l1[a], l2[a], l3[a])
Output:
10 5 20
20 9 40
30 8 60
40 2 80
45 10 100
50 89 49
45 10 100
Python Tuple
Python Tuple is used to store the sequence of immutable Python objects. The tuple is
similar to lists since the value of the items stored in the list can be changed, whereas the
tuple is immutable, and the value of the items stored in the tuple cannot be changed.
Creating a tuple
A tuple can be written as the collection of comma-separated (,) values enclosed with the
small () brackets. The parentheses are optional but it is good practice to use. A tuple can
be defined as follows.
Output:
<class 'tuple'>
<class 'tuple'>
<class 'tuple'>
Example - 2
2. print(tuple1)
3. count = 0
4. for i in tuple1:
6. count = count+1
Output:
The items in the tuple can be accessed by using the index [] operator. Python also allows
us to use the colon operator to access multiple items in the tuple.
Consider the following image to understand the indexing and slicing in detail.
Python tutorial
1. tup = (1,2,3,4,5,6,7)
2. print(tup[0])
3. print(tup[1])
4. print(tup[2])
print(tup[8])
Output:
1
2
3
tuple index out of range
In the above code, the tuple has 7 elements which denote 0 to 6. We tried to access an
Python tutorial
1. tuple = (1,2,3,4,5,6,7)
2. #element 1 to end
3. print(tuple[1:])
4. #element 0 to 3 element
5. print(tuple[:4])
6. #element 1 to 4 element
7. print(tuple[1:5])
9. print(tuple[0:6:2])
Output:
(2, 3, 4, 5, 6, 7)
(1, 2, 3, 4)
(1, 2, 3, 4)
(1, 3, 5)
Output:
(2, 4, 6, 7, 5, 1, 5, 9, 2, 0)
(2, 4, 6, 7, 5, 2, 4, 6, 7, 5)
True
1 The literal syntax of list is shown by the []. The literal syntax of the tuple is shown by the ().
3 The List has the a variable length. The tuple has the fixed length.
Python tutorial
4 The list provides more functionality than a tuple. The tuple provides less functionality than the list.
5 The list is used in the scenario in which we need to The tuple is used in the cases where we need to store the
store the simple collections with no constraints where read-only collections i.e., the value of the items cannot be
the value of the items can be changed. changed. It can be used as the key inside the dictionary.
6 The lists are less memory efficient than a tuple. The tuples are more memory efficient because of its
immutability.
Python Dictionary
Python Dictionary is used to store the data in a key-value pair format. The dictionary is
the data type in Python, which can simulate the real-life data arrangement where some
specific value exists for some particular key. It is the mutable data-structure. The
dictionary is defined into element Keys and values.
Example:
D2 = {"Hariom":"Samosa",
"Raj":{"Brake fast":"Breade", "Lunch":"Roti", "Dinner":"Halwa"},
"Abhishek":"Kachori",
"Pooja":"Jalebi",
"Harish":"Hot dog", "Sahil":"Sigrate"}
{'Hariom': 'Blue', 'Abhishek': 'Red', 'Pooja': 'Pink', 'Harish': 'Green', 'Sahil': 'Orange'}
{'Hariom': 'Blue', 'Abhishek': 'Red', 'Pooja': 'Pink', 'Harish': 'Green', 'Rahul': 'Yellow',
'Nitin': 'Black'}
Raj follow the Following schedule: {'Brake fast': 'Breade', 'Lunch': 'Roti', 'Dinner':
'Halwa'}
Syntax:
Python provides the built-in function dict() method which is also used to create
dictionary. The empty curly braces {} is used to create empty dictionary.
2. Dict = {}
4. print(Dict)
5.
6. # Creating a Dictionary
10. print(Dict)
11.
16. print(Dict)
Output:
Empty Dictionary:
{}
Iterating Dictionary
A dictionary can be iterated using for loop as given below.
Example 1
# for loop to print all the keys of a dictionary
2. for x in Employee:
3. print(x)
Output:
Name
Age
salary
Company
Python tutorial
Example 2
#for loop to print all the values of the dictionary
2. for x in Employee:
3. print(Employee[x])
Output:
John
29
25000
1. Employee={"Name":"John","Age":29,"Salary":25000,"Company":"GOOGLE","Name"
:"John"}
3. print(x,y)
Output:
Name John
Age 29
Salary 25000
Company GOOGLE
2. In python, the key cannot be any mutable object. We can use numbers, strings, or
tuples as the key, but we cannot use any mutable object like the list as the key in the
dictionary.
[100,201,301]:"Department ID"}
3. print(x,y)
Output:
1 cmp(dict1, dict2)
Compares elements of both dict.
2 len(dict)
Gives the total length of the dictionary. This would be equal to the number of
items in the dictionary.
3 str(dict)
Produces a printable string representation of a dictionary
4 type(variable)
Returns the type of the passed variable. If passed variable is dictionary, then it
would return a dictionary type.
1 dict.clear()
Removes all elements of dictionary dict
2 dict.copy()
Returns a shallow copy of dictionary dict
3 dict.fromkeys()
Create a new dictionary with keys from seq and values SET TO VALUE.
4 dict.get(key, default=None)
For key key, returns value or default if key not in dictionary
5 dict.has_key(key)
Returns true if key in dictionary DICT, FALSE otherwise
6 dict.items()
Returns a list of DICT’S (key, value) tuple pairs
7 dict.keys()
Returns list of dictionary dict’s keys
8 dict.setdefault(key, default=None)
Similar to get(), but will set dict[key]=default if key is not already in dict
9 dict.update(dict2)
Adds dictionary DICT2’S key-values pairs to DICT
10 dict.values()
Python tutorial
Example:
D1 = {"Hariom":"Blue","Abhishek":"Red", "Pooja":"Pink", "Harish":"Green", "Sahil":"Orange"}
D2 = D1.copy() # Copy D1 Dictionary in D2 as a reference by using D2 pointer
del D1["Abhishek"] # Delete Abhishek key and it's value
print(D2)
print(D1) # Abhishek has been deleted from Dictionary
print(D1.get("Hariom")) # Return value of Hariom key
D1.update({"Nikhil":"Purple"}) # Update D1 Dictionary and add one more key "Nikhil"
D1.update({"Shyam":"White"}) # Update D1 Dictionary and add one more key "Shyam"
print("Now D1 Looks Like This: ", D1)
print("All Keys which are present in dictionary: ", D1.keys()) # Print all keys of dictionary
print("All Values which are present in dictionary: ", D1.values()) # print all values of dictionary
print("All Items which are present in dictionary: ", D1.items()) # print all Keys-values pairs of
dictionary
Output:
{'Hariom': 'Blue', 'Abhishek': 'Red', 'Pooja': 'Pink', 'Harish': 'Green', 'Sahil': 'Orange'}
{'Hariom': 'Blue', 'Pooja': 'Pink', 'Harish': 'Green', 'Sahil': 'Orange'}
Blue
Now D1 Looks Like This: {'Hariom': 'Blue', 'Pooja': 'Pink', 'Harish': 'Green', 'Sahil': 'Orange', 'Nikhil': 'Purple', 'Shyam': 'White'}
All Keys which are present in dictionary: dict_keys(['Hariom', 'Pooja', 'Harish', 'Sahil', 'Nikhil', 'Shyam'])
All Values which are present in dictionary: dict_values(['Blue', 'Pink', 'Green', 'Orange', 'Purple', 'White'])
All Items which are present in dictionary: dict_items([('Hariom', 'Blue'), ('Pooja', 'Pink'), ('Harish', 'Green'), ('Sahil', 'Orange'), ('Nikhil',
'Purple'), ('Shyam', 'White')])
Python Set
A Python set is the collection of the unordered items. Each element in the set must be
unique, immutable, and the sets remove the duplicate elements. Sets are mutable which
means we can modify it after its creation.
Unlike other collections in Python, there is no index attached to the elements of the set,
i.e., we cannot directly access any element of the set by the index. However, we can
print them all together, or we can get the list of elements by looping through the set.
Creating a set
The set can be created by enclosing the comma-separated immutable items with the
curly braces {}. Python also provides the set() method, which can be used to create the
set by the passed sequence.
Python tutorial
2. print(Days)
3. print(type(Days))
5. for i in Days:
6. print(i)
Output:
Output:
Type of s1 is: <class 'set'>
Type of s2 is: <class 'set'>
If the key to be deleted from the set using discard() doesn't exist in the set, the Python
will not give the error. The program maintains its control flow.
On the other hand, if the item to be deleted from the set using remove() doesn't exist in
the set, the Python will raise an error.
2. Days2 = {"Friday","Saturday","Sunday"}
Output:
Python also provides the union() method which can also be used to calculate the union
of two sets. Consider the following example.
1. Days1 = {"Monday","Tuesday","Wednesday","Thursday"}
2. Days2 = {"Friday","Saturday","Sunday"}
Output:
Output:
{'Monday', 'Tuesday'}
Output:
{'Martin', 'David'}
Example 3:
1. set1 = {1,2,3,4,5,6,7}
2. set2 = {1,2,20,32,5,9}
3. set3 = set1.intersection(set2)
4. print(set3)
Output:
{1,2,5}
4.
5. a.intersection_update(b, c)
6.
7. print(a)
Output:
Python tutorial
{'castle'}
Output:
{'Thursday', 'Wednesday'}
ays2
Output:
{'Thursday', 'Wednesday'}
1. a = {1,2,3,4,5,6}
2. b = {1,2,9,8,10}
3. c = a^b
4. print(c)
Output:
{3, 4, 5, 6, 8, 9, 10}
1. a = {1,2,3,4,5,6}
Python tutorial
2. b = {1,2,9,8,10}
3. c = a.symmetric_difference(b)
4. print(c)
Output:
{3, 4, 5, 6, 8, 9, 10}
Set comparisons
Python allows us to use the comparison operators i.e., <, >, <=, >= , == with the sets
by using which we can check whether a set is a subset, superset, or equivalent to other
set. The boolean true or false is returned depending upon the items present inside the
sets.
4.
6. print (Days1>Days2)
7.
9. print (Days1<Days2)
10.
11. #prints false since Days2 and Days3 are not equivalent
Output:
Python tutorial
True
False
False
FrozenSets
The frozen sets are the immutable form of the normal sets, i.e., the items of the frozen
set cannot be changed and therefore it can be used as a key in the dictionary.
The elements of the frozen set cannot be changed after the creation. We cannot change
or append the content of the frozen sets by using the methods like add() or remove().
The frozenset() method is used to create the frozenset object. The iterable sequence is
passed into this method which is converted into the frozen set as a return type of the
method.
1. Frozenset = frozenset([1,2,3,4,5])
2. print(type(Frozenset))
4. for i in Frozenset:
5. print(i);
Output:
<class 'frozenset'>
2. print(type(Dictionary))
4. print(type(Frozenset))
5. for i in Frozenset:
print(i)
Output:
<class 'dict'>
<class 'frozenset'>
Name
Country
ID
SN Method Description
1 add(item) It adds an item to the set. It has no effect if the item is already present in the set.
4 difference_update(....) It modifies this set by removing all the items that are also present in the specified
sets.
7 intersection_update(....) It removes the items from the original set that are not present in both the sets (all
the sets if more than one are specified).
11 pop() Remove and return an arbitrary set element that is the last element of the set.
Raises KeyError if the set is empty.
12 remove(item) Remove an element from a set; it must be a member. If the element is not a
member, raise a KeyError.
13 symmetric_difference(....) Remove an element from a set; it must be a member. If the element is not a
member, raise a KeyError.
14 symmetric_difference_update(....) Update a set with the symmetric difference of itself and another.
Statement Description
If - else The if-else statement is similar to if statement except the fact that, it
Statement also provides the block of the code for the false case of the condition
to be checked. If the condition provided in the if statement is false,
then the else statement will be executed.
Python tutorial
Nested if Nested if statements enable us to use if ? else statement inside an
Statement outer if statement.
The if statement
The if statement is used to test a particular condition and if the condition is true, it
executes a block of code known as if-block. The condition of if statement can be any valid
logical expression which can be either evaluated to true or false.
1. if expression:
2. statement
Example:
2. if num%2 == 0:
3. print("Number is even")
Output:
If the condition is true, then the if-block is executed. Otherwise, the else-block is
executed.
Python tutorial
1. if condition:
2. #block of statements
3. else:
2. if age>=18:
4. else:
Output:
The elif statement works like an if-else-if ladder statement in C. It must be succeeded by
an if statement.
1. if expression 1:
2. # block of statements
3.
4. elif expression 2:
5. # block of statements
6.
7. elif expression 3:
8. # block of statements
Python tutorial
9.
10. else:
Example :
marks = int(input("Enter the marks? "))
if marks > 85 and marks <= 100:
print("Congrats ! you scored grade A ...")
elif marks > 60 and marks <= 85:
print("You scored grade B + ...")
elif marks > 40 and marks <= 60:
print("You scored grade B ...")
elif (marks > 30 and marks <= 40):
print("You scored grade C ...")
else:
print("Sorry you are fail ?")
Output:
Python tutorial
if "Apple" in list1:
print("Apple is present in the list")
else:
print("Apple is not present in the list")
Output:
Apple is present in the list
Python Loops
The flow of the programs written in any programming language is sequential by default.
Sometimes we may need to alter the flow of the program. The execution of a specific
code may need to be repeated several numbers of times.
For this purpose, The programming languages provide various types of loops which are
capable of repeating some specific code several numbers of times. Consider the following
diagram to understand the working of a loop statement.
Python tutorial
Advantages of loops
There are the following advantages of loops in Python.
Loop Description
Statement
for loop The for loop is used in the case where we need to execute some part
of the code until the given condition is satisfied. The for loop is also
called as a per-tested loop. It is better to use for loop if the number of
iteration is known in advance.
while loop The while loop is to be used in the scenario where we don't know the
number of iterations in advance. The block of statements is executed
in the while loop until the condition specified in the while loop is
satisfied. It is also called a pre-tested loop.
1. str = "Python"
2. for i in str:
3. print(i)
Output:
P
Python tutorial
y
t
h
o
n
1. list = [1,2,3,4,5,6,7,8,9,10]
2. n = 5
3. for i in list:
4. c = n*i
5. print(c)
Output:
5
10
15
20
25
30
35
40
45
50s
1. list = [10,30,23,43,65,12]
2. sum = 0
3. for i in list:
4. sum = sum+i
5. print("The sum is:",sum)
Output:
The range() function is used to generate the sequence of the numbers. If we pass the
range(10), it will generate the numbers from 0 to 9. The syntax of the range() function is
given below.
Python tutorial
Syntax:
1. range(start,stop,step size)
1. for i in range(10):
2. print(i,end = ' ')
Output:
0 1 2 3 4 5 6 7 8 9
Output:
Output:
We can also use the range() function with sequence of numbers. The len() function is
combined with range() function which iterate through a sequence using indexing.
Consider the following example.
1. list = ['Peter','Joseph','Ricky','Devansh']
2. for i in range(len(list)):
3. print("Hello",list[i])
Output:
Hello Peter
Hello Joseph
Hello Ricky
Hello Devansh
Syntax
Output:
Output:
1
22
333
4444
55555
Example 1
1. for i in range(0,5):
2. print(i)
3. else:
4. print("for loop completely exhausted, since there is no break.")
Output:
0
1
2
3
4
for loop completely exhausted, since there is no break.
Example 2
1. for i in range(0,5):
2. print(i)
3. break;
4. else:print("for loop is exhausted");
5. print("The loop is broken due to break statement...came out of the loop")
In the above example, the loop is broken due to the break statement; therefore, the else
statement will not be executed. The statement present immediate next to else block will
be executed.
Output:
Example 3:
list1 = ["Mango", "Apple", "Banana", "Pineapple", "Papaya", "Orange", "Plum", "Guava", "Grapes"]
for i in list1:
if i == "Chiku":
print("Item found!")
break
else:
Python tutorial
print("item not found!")
Output:
item not found!
1. while expression:
2. statements
Here, the statements can be a single statement or a group of statements. The expression
should be any valid Python expression resulting in true or false. The true is any non-zero
value and false is 0.
1. i = 0
2. while(i < 10):
3. i = i+1
4. if(i == 5):
5. continue
6. print(i)
Output:
1
2
3
4
6
7
8
9
10
2. Break Statement - When the break statement is encountered, it brings control out of
the loop.
Example:
1. n=2
2. while 1:
3. i=1;
4. while i<=10:
5. print("%d X %d = %d\n"%(n,i,n*i));
6. i = i+1;
7. choice = int(input("Do you want to continue printing the table, press 0 for no?"))
8. if choice == 0:
9. break;
10. n=n+1
Output:
2 X 1 = 2
2 X 2 = 4
2 X 3 = 6
Python tutorial
2 X 4 = 8
2 X 5 = 10
2 X 6 = 12
2 X 7 = 14
2 X 8 = 16
2 X 9 = 18
2 X 10 = 20
3 X 1 = 3
3 X 2 = 6
3 X 3 = 9
3 X 4 = 12
3 X 5 = 15
3 X 6 = 18
3 X 7 = 21
3 X 8 = 24
3 X 9 = 27
3 X 10 = 30
3. Pass Statement - In Python, the pass keyword is used to execute nothing; it means,
when we don't want to execute code, the pass can be used to execute empty. It is the
same as the name refers to. It just makes the control to pass by without executing any
code. If we want to bypass any code pass statement can be used.
Output:
Example - 2:
for i in [1,2,3,4,5]:
if(i==4):
pass
print("This is pass block",i)
print(i)
Output:
1
2
3
This is pass block 4
4
5
# Empty Function
def function_name(args):
pass
#Empty Class
class Python:
pass
1. i=1
2. #The while loop will iterate until condition becomes false.
Python tutorial
3. While(i<=10):
4. print(i)
5. i=i+1
Output:
1
2
3
4
5
6
7
8
9
10
Output:
Enter the number:25
25 X 1 = 25
25 X 2 = 50
25 X 3 = 75
25 X 4 = 100
25 X 5 = 125
25 X 6 = 150
25 X 7 = 175
25 X 8 = 200
25 X 9 = 225
25 X 10 = 250
Output:
1
2
3
4
Python tutorial
5
Any non-zero value in the while loop indicates an always-true condition, whereas zero
indicates the always-false condition. This type of approach is useful if we want our
program to run continuously in the loop without any disturbance.
Example:
while (1):
print("Hi! we are inside the infinite while loop")
Output:
Example:
i = 0
while True:
if i <= 10:
i += 1
continue
if i == 50:
break
i += 1
Output:
Python tutorial
11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50
Python Function
Functions are the most important aspect of an application. A function can be defined as
the organized block of reusable code, which can be called whenever required.
Python allows us to divide a large program into the basic building blocks known as a
function. The function contains the set of programming statements enclosed by {}. A
function can be called multiple times to provide reusability and modularity to the Python
program.
Python provide us various inbuilt functions like range() or print(). Although, the user
can create its functions, which can be called user-defined functions.
o Using functions, we can avoid rewriting the same logic/code again and again in a
program.
o We can call Python functions multiple times in a program and anywhere in a
program.
o We can track a large Python program easily when it is divided into multiple
functions.
o Reusability is the main achievement of Python functions.
Python tutorial
Creating a Function
Python provides the def keyword to define the function. The syntax of the define function
is given below.
Syntax:
1. def my_function(parameters):
2. function_block
3. return expression
Function Calling
In Python, after the function is created, we can call it from another function. A function
must be defined before the function call; otherwise, the Python interpreter gives an error.
To call the function, use the function name followed by the parentheses.
Consider the following example of a simple example that prints the message "Hello
World".
1. #function definition
2. def hello_world():
3. print("hello world")
4. # function calling
5. hello_world()
Output:
hello world
Syntax
Python tutorial
1. return [expression_list]
It can contain the expression which gets evaluated and value is returned to the caller
function. If the return statement has no expression or does not exist itself in the function
then it returns the None object.
Example 1
1. # Defining function
2. def sum():
3. a = 10
4. b = 20
5. c = a+b
6. return c
7. # calling sum() function in print statement
8. print("The sum is:",sum())
Output:
In the above code, we have defined the function named sum, and it has a statement c =
a+b, which computes the given values, and the result is returned by the return
statement to the caller function.
1. # Defining function
2. def sum():
3. a = 10
4. b = 20
5. c = a+b
6. # calling sum() function in print statement
7. print(sum())
Output:
None
In the above code, we have defined the same function without the return statement as
Python tutorial
we can see that the sum() function returned the None object to the caller function.
Arguments in function
The arguments are types of information which can be passed into the function. The
arguments are specified in the parentheses. We can pass any number of arguments, but
they must be separate them with a comma.
Example:
Output:
Enter a: 10
Enter b: 20
Sum = 30
Output:
Output:
Example:
def Avg(a, b):
"""This is a function which calculates the average of two numbers"""
# The above line is not a comment, it is a doc string of a function
avg = (a + b)/2
return avg
print(Avg.__doc__)
x = float(input("Enter first number: "))
y = float(input("Enter second number: "))
ans = Avg(x, y)
print("Average = ", ans)
Output:
This is a function which calculates the average of two numbers
Enter first number: 45
Enter second number: 54
Average = 49.5
Types of arguments
There may be several types of arguments which can be passed at the time of function
call.
Python tutorial
1. Required arguments
2. Keyword arguments
3. Default arguments
4. Variable-length arguments
Required Arguments
However, we can provide the arguments at the time of the function call. As far as the required
arguments are concerned, these are the arguments which are required to be passed at the time
of function calling with the exact match of their positions in the function call and function
definition. If either of the arguments is not provided in the function call, or the position of the
arguments is changed, the Python interpreter will show the error.
Example 1
1. def func(name):
2. message = "Hi "+name
3. return message
4. name = input("Enter the name:")
5. print(func(name))
Output:
Example 2
1. #the function simple_interest accepts three arguments and returns the simple inter
est accordingly
2. def simple_interest(p,t,r):
3. return (p*t*r)/100
4. p = float(input("Enter the principle amount? "))
5. r = float(input("Enter the rate of interest? "))
6. t = float(input("Enter the time in years? "))
7. print("Simple Interest: ",simple_interest(p,r,t))
Output:
Default Arguments
Python allows us to initialize the arguments at the function definition. If the value of any
of the arguments is not provided at the time of function call, then that argument can be
initialized with the value given in the definition even if the argument is not specified at
the function call.
Example:
1. def printme(name,age=22):
2. print("My name is",name,"and age is",age)
3. printme(name = "john") #the variable age is not passed into the function however
the default value of age is considered in the function
4. printme(age = 10,name="David") #the value of age is overwritten here, 10 will be
printed as age
Output:
Example 1:
1. def printme(*names):
2. print("type of passed argument is ",type(names))
3. print("printing the passed arguments...")
4. for name in names:
Python tutorial
5. print(name)
6. printme("john","David","smith","nick")
Output:
Example 2:
def calculate(*args):
sum=0
for arg in args:
sum = sum +arg
print("The sum is",sum)
Output:
Keyword arguments(**kwargs)
Python allows us to call the function with the keyword arguments. This kind of function
call will enable us to pass the arguments in the random order.
The name of the arguments is treated as the keywords and matched in the function
calling and definition. If the same match is found, the values of the arguments are copied
in the function definition.
Python provides the facility to pass the multiple keyword arguments which can be
represented as **kwargs. It is similar as the *args but it stores the argument in the
dictionary format.
This type of arguments is useful when we do not know the number of arguments in
advance.
Output:
{'a': 'Apple'}
{'fruits': 'Orange', 'Vagitables': 'Carrot'}
print("Using args:")
args = ("Hariom", "Singh", "Rajput")
myFun(*args)
print("\nUsing kwargs:")
kwargs = {"arg1":"Hariom", "arg2":"Singh", "arg3":"Rajput"}
myFun(**kwargs)
Output:
Using args:
First Name: Hariom
Middle Name: Singh
Last Name: Rajput
Using kwargs:
First Name: Hariom
Python tutorial
1. # integer number
2. integer = -20
3. print('Absolute value of -20 is:', abs(integer))
4.
5. # floating number
6. floating = -20.83
7. print('Absolute value of -20.83 is:', abs(floating))
Output:
1. x = 10
Python tutorial
2. y = bin(x)
3. print (y)
Output:
0b1010
Output:
123
123.456790
1100
1. # list of numbers
2. list = [1,2,3,4,5]
Python tutorial
3.
4. listIter = iter(list)
5.
6. # prints '1'
7. print(next(listIter))
8.
9. # prints '2'
10. print(next(listIter))
11.
12. # prints '3'
13. print(next(listIter))
14.
15. # prints '4'
16. print(next(listIter))
17.
18. # prints '5'
19. print(next(listIter))
Output:
1
2
3
4
5
1. strA = 'Python'
2. print(len(strA))
Output:
6
Python tutorial
Python list()
The python list() creates a list in python.
1. # empty list
2. print(list())
3.
4. # string
5. String = 'abcde'
6. print(list(String))
7.
8. # tuple
9. Tuple = (1,2,3,4,5)
10. print(list(Tuple))
11. # list
12. List = [1,2,3,4,5]
13. print(list(List))
Output:
[]
['a', 'b', 'c', 'd', 'e']
[1,2,3,4,5]
[1,2,3,4,5]
Python complex()
Python complex() function is used to convert numbers or string into a complex number.
This method takes two optional parameters and returns a complex number. The first
parameter is called a real and second as imaginary parts.
Output:
(1.5+0j)
(1.5+2.2j)
The first argument can be none, if the function is not available and returns only elements
that are true.
Output:
[6]
compare dictionary keys during a dictionary lookup. We can hash only the types which
are given below:
Hashable types: * bool * int * long * float * string * Unicode * tuple * code object.
1. # Calling function
2. result = hash(21) # integer value
3. result2 = hash(22.2) # decimal value
4. # Displaying result
5. print(result)
6. print(result2)
Output:
21
461168601842737174
1. # Calling function
2. small = min(2225,325,2025) # returns smallest element
3. small2 = min(1000.25,2025.35,5625.36,10052.50)
4. # Displaying result
5. print(small)
6. print(small2)
Output:
325
1000.25
Python tutorial
Python set() Function
In python, a set is a built-in class, and this function is a constructor of this class. It is used
to create a new set using elements passed during the call. It takes an iterable object as
an argument and returns a new set object.
# Calling function
result = set() # empty set
result2 = set('12')
result3 = set('Hariom')
# Displaying result
print(result)
print(result2)
print(result3)
Output:
set()
{'1', '2'}
{'H', 'm', 'a', 'o', 'i', 'r'}
1. # Calling function
2. result = hex(1)
3. # integer value
4. result2 = hex(342)
5. # Displaying result
6. print(result)
7. print(result2)
Output:
Python tutorial
0x1
0x156
Output:
[' ', '-', '1', '2', '3', '4', '5', '@', 'H', 'R', 'S', '_', 'a', 'a', 'g', 'h', 'i', 'i', 'j',
'm', 'n', 'o', 'p', 'r', 't', 'u']
This method calls on iterator and throws an error if no item is present. To avoid the error,
we can set a default value.
Output:
256
32
82
1. # Calling function
2. val = input("Enter a value: ")
3. # Displaying result
4. print("You entered:",val)
Output:
Enter a value: 45
You entered: 45
1. # Calling function
2. val = oct(10)
3. # Displaying result
4. print("Octal value of 10:",val)
Python tutorial
Output:
Output:
56
82
38
Output:
16
16
0.0625
0.0625
1. # empty range
2. print(list(range(0)))
3.
4. # using the range(stop)
5. print(list(range(4)))
6.
7. # using the range(start, stop)
8. print(list(range(1,7 )))
Output:
[]
[0, 1, 2, 3]
[1, 2, 3, 4, 5, 6]
The python reversed() function returns the reversed iterator of the given sequence.
1. # for string
2. String = 'Java'
3. print(list(reversed(String)))
4.
5. # for tuple
6. Tuple = ('J', 'a', 'v', 'a')
7. print(list(reversed(Tuple)))
8.
9. # for range
10. Range = range(8, 12)
11. print(list(reversed(Range)))
12.
13. # for list
14. List = [1, 2, 7, 5]
15. print(list(reversed(List)))
Output:
1. # for integers
2. print(round(10))
3.
4. # for floating point
Python tutorial
5. print(round(10.8))
6.
7. # even choice
8. print(round(6.6))
Output:
10
11
7
Python str
The python str() converts a specified value into a string.
1. str('4')
Output:
'4'
1. t1 = tuple()
2. print('t1=', t1)
3.
4. # creating a tuple from a list
5. t2 = tuple([1, 6, 9])
6. print('t2=', t2)
7.
8. # creating a tuple from a string
9. t1 = tuple('Java')
10. print('t1=',t1)
Python tutorial
11.
12. # creating a tuple from a dictionary
13. t1 = tuple({4: 'four', 5: 'five'})
14. print('t1=',t1)
Output:
t1= ()
t2= (1, 6, 9)
t1= ('J', 'a', 'v', 'a')
t1= (4, 5)
Recursion in python:
The term Recursion can be defined as the process of defining
something in terms of itself. In simple words, it is a process in
which a function calls itself directly or indirectly.
def factorial_recursive(n):
"""
This a recursive method for factorial of a number
"""
if n == 1 or n == 0:
return 1
else:
return n * factorial_recursive(n-1)
Output:
Enter a number: 6
Factorial using iterative method:
Factorial of 6 is: 720
Example2:
def febonacci(n):
if n == 0:
return 0
elif n == 1:
return 1
else:
return febonacci(n-1) + febonacci(n-2)
Output:
Enter a number: 10
Your fibonacci series is:
0 1 1 2 3 5 8 13 21 34
The anonymous function contains a small piece of code. It simulates inline functions of C
and C++, but it is not exactly an inline function.
Syntax
It can accept any number of arguments and has only one expression. It is useful when
the function objects are required.
Example 1
# Lambda function is also known as anonymous function
# This is a one liner function
add = lambda x, y: x + y
minus = lambda x, y: x - y
product = lambda x, y: x * y
divide = lambda x, y: x / y
Output:
Enter first number:45
Enter second number:12
Addition of 45.0 and 12.0 is: 57.0
Subtraction of 45.0 and 12.0 is: 33.0
Multiplication of 45.0 and 12.0 is: 540.0
Division of 45.0 and 12.0 is: 3.75
Example 2: lambda function with sort()
a = [[3, 4], [6, 9], [2, 1], [11, 32], [98, 76], [54, 23]]
a.sort(key=lambda x: x[1]) # this lambda function will sort x[1] index values not x[0]
print(a)
Output:
Python tutorial
[[2, 1], [3, 4], [6, 9], [54, 23], [11, 32], [98, 76]]
Example 3: lambda function with filter()
list1 = [12, 34, 98, 65, 3, 1, 2, 54, 9, 0, 87, 465, 45, 3, 2, 4, 75, 23, 45, 56, 78, 90, 100, 65,
24, 14]
odd_number = list(filter(lambda x: (x%2 != 0), list1))
even_number = list(filter(lambda x: (x%2 == 0), list1))
print("Odd numbers present in list1: ", odd_number)
print("Even numbers present in list1: ", even_number)
Output:
Odd numbers present in list1: [65, 3, 1, 9, 87, 465, 45, 3, 75,
23, 45, 65]
Even numbers present in list1: [12, 34, 98, 2, 54, 0, 2, 4, 56, 78,
90, 100, 24, 14]
Example 4: lambda function with map()
List = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
power = list(map(lambda x: x*x, List))
print("Squares are: ", power)
Output:
Squares are: [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
Python Exception
An exception can be defined as an unusual condition in a program resulting in the
interruption in the flow of the program.
Whenever an exception occurs, the program stops the execution, and thus the further
code is not executed. Therefore, an exception is the run-time errors that are unable to
handle to Python script. An exception is a Python object that represents an error
Python provides a way to handle the exception so that the code can be executed without
Python tutorial
any interruption. If we do not handle the exception, the interpreter doesn't execute all
the code that exists after the exception.
Python has many built-in exceptions that enable our program to run without
interruption and give the output. These exceptions are given below:
Common Exceptions
Python provides the number of built-in exceptions, but here we are describing the
common standard exceptions. A list of common exceptions that can be thrown from a
standard Python program is given below.
Example
1. a = int(input("Enter a:"))
2. b = int(input("Enter b:"))
3. c = a/b
4. print("a/b = %d" %c)
5.
6. #other code:
7. print("Hi I am other part of the program")
Python tutorial
Output:
Enter a:10
Enter b:0
Traceback (most recent call last):
File "exception-test.py", line 3, in <module>
c = a/b;
ZeroDivisionError: division by zero
The above program is syntactically correct, but it through the error because of unusual
input. That kind of programming may not be suitable or recommended for the projects
because these projects are required uninterrupted execution. That's why an exception-
handling plays an essential role in handling these unexpected exceptions. We can handle
these exceptions in the following way.
Syntax
1. try:
2. #block of code
3.
4. except Exception1:
Python tutorial
5. #block of code
6.
7. except Exception2:
8. #block of code
9.
10. #other code
Example 1
1. try:
2. a = int(input("Enter a:"))
3. b = int(input("Enter b:"))
4. c = a/b
5. except:
6. print("Can't divide with zero")
Output:
Enter a:10
Enter b:0
Can't divide with zero
We can also use the else statement with the try-except statement in which, we can place
the code which will be executed in the scenario if no exception occurs in the try block.
The syntax to use the else statement with the try-except statement is given below.
1. try:
2. #block of code
3.
4. except Exception1:
5. #block of code
6.
7. else:
8. #this code executes if no except block is executed
Python tutorial
Example 2
1. try:
2. a = int(input("Enter a:"))
3. b = int(input("Enter b:"))
4. c = a/b
5. print("a/b = %d"%c)
6. # Using Exception with except statement. If we print(Exception) it will return excep
tion class
7. except Exception:
8. print("can't divide by zero")
9. print(Exception)
10. else:
11. print("Hi I am else block")
Output:
Enter a:10
Enter b:0
Python tutorial
can't divide by zero
<class 'Exception'>
Example:
try:
a = int(input("Enter a:"))
b = int(input("Enter b:"))
c = a/b
print("a/b = %d"%c)
# Using exception object with the except statement
except Exception as e:
print("We can not divide this value by zero")
print(e)
else:
print("Hi I am else block")
Output:
Enter a:10
Enter b:0
can't divide by zero
division by zero
Points to remember
1. Python facilitates us to not specify the exception with the except statement.
2. We can declare multiple exceptions in the except statement since the try block
may contain the statements which throw the different type of exceptions.
3. We can also specify an else block along with the try-except statement, which will
be executed if no exception is raised in the try block.
4. The statements that don't throw the exception should be placed inside the else
block.
Example
1. try:
2. #this will throw an exception if the file doesn't exist.
3. fileptr = open("file.txt","r")
4. except IOError:
Python tutorial
5. print("File not found")
6. else:
7. print("The file opened successfully")
8. fileptr.close()
Output:
We can use the finally block with the try block in which we can pace the necessary code,
which must be executed before the try statement throws an exception.
Syntax
1. try:
2. # block of code
3. # this may throw an exception
4. finally:
5. # block of code
6. # this will always be executed
Python tutorial
Example 1:
1. try:
2. fileptr = open("file2.txt","r")
3. try:
4. fileptr.write("Hi I am good")
5. finally:
6. fileptr.close()
7. print("file closed")
8. except:
9. print("Error")
Python tutorial
Output:
file closed
Error
Example 2:
a = input("Enter first number: ")
b = input("Enter second number: ")
try:
print("The sum of these two numbers is: ", int(a) / int(b))
finally:
print("This is the final block!")
print("Error found!")
Output:
Enter first number: 5
Enter second number: 0
This is the final block!
Traceback (most recent call last):
File "A:\Python Tutorial\9. Exception Handling\
2_Finally_block.py", line 5, in <module>
print("The sum of these two numbers is: ", int(a) / int(b))
ZeroDivisionError: division by zero
Raising exceptions
An exception can be raised forcefully by using the raise clause in Python. It is useful in in
that scenario where we need to raise an exception to stop the execution of the program.
For example, there is a program that requires 2GB memory for execution, and if the
program tries to occupy 2GB of memory, then we can raise an exception to stop the
Python tutorial
Syntax
1. raise Exception_class,<value>
Points to remember
1. To raise an exception, the raise statement is used. The exception class name
follows it.
2. An exception can be provided with a value that can be given in the parenthesis.
3. To access the value "as" keyword is used. "e" is used as a reference variable which
stores the value of the exception.
4. We can pass the value to an exception to specify the exception type.
Example
1. try:
2. age = int(input("Enter the age:"))
3. if(age<18):
4. raise ValueError
5. else:
6. print("the age is valid")
7. except ValueError:
8. print("The age is not valid")
Output:
1. try:
2. num = int(input("Enter a positive integer: "))
3. if(num <= 0):
4. # we can pass the message in the raise statement
Python tutorial
5. raise ValueError("That is a negative number!")
6. except ValueError as e:
7. print(e)
Output:
Example 3:
try:
name = input("Enter your name? : ")
if name == "Hariom" or name == "hariom" or name == 'HARIOM':
raise ValueError("Hariom is blocked!")
if name.isnumeric():
raise Exception("Numbers are not allowed.")
except ValueError as e:
print(e)
except Exception as e:
print(e)
except ZeroDivisionError as e:
print(e)
Output:
Enter your name? : hariom
Hariom is blocked!
Gate Out...
Some built-in exceptions:
try:
dict1 = {"Name": "Hariom", "Age": 19, "Skill": ['c', 'c++', 'python', 'batch scripting',
'powershell scripting']}
name = input("Enter your name : ")
Python tutorial
for i in name:
if i == '\t':
raise TabError("Tab is not allowed")
except TabError as e:
print(e)
except KeyError as e:
print(e)
Output:
Enter your name : hariom rajput
Well come hariom rajput
Enter a key: semester
'Key is not available in the dictionary'
n Python, files are treated in two modes as text or binary. The file may be in the text or
binary format, and each line of a file is ended with the special character.
o Open a file
o Read or write - Performing operation
Python tutorial
Opening a file
Python provides an open() function that accepts two arguments, file name and access
mode in which the file is accessed. The function returns a file object which can be used to
perform various operations like reading, writing, etc.
Syntax:
The files can be accessed using various modes like read, write, or append. The following
are the details about the access mode to open a file.
SN Access Description
mode
1 r It opens the file to read-only mode. The file pointer exists at the
beginning. The file is by default open in this mode if no access
mode is passed.
2 rb It opens the file to read-only in binary format. The file pointer exists
at the beginning of the file.
3 r+ It opens the file to read and write both. The file pointer exists at the
beginning of the file.
4 rb+ It opens the file to read and write both in binary format. The file
pointer exists at the beginning of the file.
6 wb It opens the file to write only in binary format. It overwrites the file
if it exists previously or creates a new one if no file exists. The file
pointer exists at the beginning of the file.
7 w+ It opens the file to write and read both. It is different from r+ in the
sense that it overwrites the previous file if one exists whereas r+
doesn't overwrite the previously written file. It creates a new file if
no file exists. The file pointer exists at the beginning of the file.
Python tutorial
8 wb+ It opens the file to write and read both in binary format. The file
pointer exists at the beginning of the file.
9 a It opens the file in the append mode. The file pointer exists at the
end of the previously written file if exists any. It creates a new file if
no file exists with the same name.
10 ab It opens the file in the append mode in binary format. The pointer
exists at the end of the previously written file. It creates a new file
in binary format if no file exists with the same name.
11 a+ It opens a file to append and read both. The file pointer remains at
the end of the file if a file exists. It creates a new file if no file exists
with the same name.
12 ab+ It opens a file to append and read both in binary format. The file
pointer remains at the end of the file.
Example:
f = open("hsr.txt", "r")
f.close()
read2.close()
Output:
Reading in text mode:
Akkad
Bakk
Python tutorial
ad Bambe Bo
80 90 pure 100
What is this! Do you know...
We can perform any operation on the file externally using the file system which is the
currently opened in Python; hence it is good practice to close the file once all the
operations are done.
Syntax
1. fileobject.close()
The syntax to open a file using with the statement is given below.
The advantage of using with statement is that it provides the guarantee to close the file
regardless of how the nested block exits.
Example:
print("Reading file by using with block\n")
with open("Hsr.txt") as f:
print(f.readline())
print(f.readline())
print(f.readline())
print(f.readline())
print(f.readline())
# There is no need to close the file
w: It will overwrite the file if any file exists. The file pointer is at the beginning of the file.
a: It will append the existing file. The file pointer is at the end of the file. It creates a new
file if no file exists.
f = open("Hariom.txt", "w")
content = f.write("My Introduction\nHello, Everyone!\nMy name is Hariom Mewada\nI am 19 years old\
nJust I am learning python.\nThank you...")
print("Write", content, "texts in Hariom.txt file")
f.close()
Python tutorial
Output:
Write 115 texts in Hariom.txt file
Read file through for loop
We can read the file using for loop. Consider the following example.
1. #open the file.txt in read mode. causes an error if no such file exists.
2. fileptr = open("file2.txt","r");
3. #running a for loop
4. for i in fileptr:
5. print(i) # i contains each line of the file
Example:
read1 = open("Hsr.txt") # by default open in "r" (read) mode
print("Reading file line by line by using for loop:")
for line in read1:
print(line)
read1.close()
read2.close()
for i in characters:
print(i, end=" ")
Python tutorial
Example:
f = open("Hariom.txt")
# tell() function is used for knowing the exact file pointer location(index number where pointer is
present).
print(f.tell())
print(f.readline())
print(f.tell())
print(f.readline())
print(f.tell())
print(f.readline())
print(f.tell())
print(f.readline())
print(f.tell())
f.close()
Output:
0
My Introduction
17
Hello, Everyone!
35
My name is Hariom Mewada
Python tutorial
61
I am 19 years old
80
For this purpose, the Python provides us the seek() method which enables us to modify
the file pointer position externally.
Example:
f = open("Hariom.txt")
print(f.tell())
print(f.readline())
f.seek(0) # This will reset the file pointer location according to index value
print(f.tell())
print(f.readline())
f.seek(17)
print(f.tell())
print(f.readline())
f.seek(35)
print(f.tell())
print(f.readline())
f.seek(17)
print(f.tell())
print(f.readline())
f.close()
Output:
Python tutorial
0
My Introduction
0
My Introduction
17
Hello, Everyone!
35
My name is Hariom Mewada
17
Hello, Everyone!
SN Method Description
Python tutorial
1 file.close() It closes the opened file. The file once closed, it can't
be read or write anymore.
7 File.readline([size]) It reads one line from the file and places the file pointer
to the beginning of the new line.
Python OS Module
Python OS module provides the facility to establish the interaction between the user and
the operating system. It offers many useful OS functions that are used to perform OS-
based tasks and get related information about operating system.
Syntax:
1. rename(current-name, new-name)
The first argument is the current file name and the second argument is the modified
name. We can change the file name bypassing these two arguments.
Example 1:
1. import os
2.
3. #rename file2.txt to file3.txt
4. os.rename("file2.txt","file3.txt")
Output:
1. remove(file-name)
Example 1
1. import os;
2. #deleting the file named file3.txt
3. os.remove("file3.txt")
Syntax:
1. mkdir(directory name)
Python tutorial
Example 1
1. import os
2.
3. #creating a new directory with the name new
4. os.mkdir("new")
Syntax
1. os.getcwd()
Example
1. import os
2. os.getcwd()
Output:
'C:\\Users\\DEVANSH SHARMA'
Syntax
1. chdir("new-directory")
Example
1. import os
2. # Changing current directory with the new directiory
Python tutorial
3. os.chdir("C:\\Users\\DEVANSH SHARMA\\Documents")
4. #It will display the current working directory
5. os.getcwd()
Output:
'C:\\Users\\DEVANSH SHARMA\\Documents'
Deleting directory
The rmdir() method is used to delete the specified directory.
Syntax
1. os.rmdir(directory name)
Example 1
1. import os
2. #removing the new directory
3. os.rmdir("directory_name")
print(result)
Output
False
Python tutorial
size = os.path.getsize("filename")
Output:
Size of the file is 192 bytes.
os.close(): Close file descriptor fd. A file opened using open(),
can be closed by close()only. But file opened through
os.popen(), can be closed with close() or os.close(). If we try
closing a file opened with open(), using os.close(), Python would
throw TypeError.
Example:
import os
fd = "GFG.txt"
file = open(fd, 'r')
text = file.read()
print(text)
os.close(file)
Output:
Python tutorial
Output:
Hello
Note: Output for popen() will not be shown, there would be
Python tutorial
# Rename a file
os.rename("Hariom.txt", "HSR.txt")
# Join paths
print(os.path.join("D:", "/HSR"))
Example1:
me = "Hariom Singh Rajput"
a = "Good Morning"
b = f"I am {me} and {a} everyone!"
print(b)
print(f"I am {me} and {a} everyone!")
Output:
I am Hariom Singh Rajput and Good Morning everyone!
I am Hariom Singh Rajput and Good Morning everyone!
Example 2:
# Prints today's date with help
# of datetime library
import datetime
today = datetime.datetime.today()
print(f"{today:%d %B, %Y}")
Output:
09 February, 2022
Formatting using format function:
Example:
# Formating using format function
me = "Hariom Singh Rajput"
a = "Good Morning"
b = "Hello! {} {}"
c = b.format(me, a)
print(c)
Output:
Hello! Hariom Singh Rajput Good Morning
Python tutorial
Note : F-strings are faster than the two most commonly used
string formatting mechanisms, which are % formatting and
str.format().
random.random()
This function generates a random float number between 0.0 and 1.0.
random.randint()
This function returns a random integer between the specified integers.
random.choice()
This function returns a randomly selected element from a non-empty sequence.
rand = random.random() * 100 # Generate a floating point random number between 0 to 100
print("Floating point random number is: ", rand)
print(random.random()) # this will print a random number between 0 to 1
Output:
Python tutorial
Seed() function:
if the seeding any value then the output of the program will
always be the same.
Example:
import random
random.seed(2)
print(random.random())
print(random.random())
Output:
0.9560342718892494
0.9478274870593494
Choice() function:
It is used for selecting random elements from the list, string, and
tuple.
Example:
import random
Output:
Will you watch zee cinema ?
Shuffling List
random.shuffle() method is used to shuffle a sequence (list).
Shuffling means changing the position of the elements of the
sequence. Here, the shuffling operation is inplace.
Syntax:
random.shuffle(sequence, function)
Example:
# import the random module
import random
# declare a list
sample_list = [1, 2, 3, 4, 5]
# first shuffle
random.shuffle(sample_list)
print("\nAfter the first shuffle : ")
print(sample_list)
# second shuffle
random.shuffle(sample_list)
print("\nAfter the second shuffle : ")
print(sample_list)
Output:
Python tutorial
Original list :
[1, 2, 3, 4, 5]
Randrange():
It returns a random number within the range
Example:
import random
Output:
Random number from 0-100 is : 26
Random number from 50-100 is : 58
Random number from 50-100 skip 5 is : 90
random.choices()
The choices() method returns multiple random elements from
the list with replacement.
Example:
import random
mylist = ["apple", "banana", "mango", "guava"]
print(random.choices(mylist, k=6))
Output:
['guava', 'banana', 'banana', 'apple', 'guava', 'apple']
Sample() method:
sample() is an inbuilt function of random module in Python that
returns a particular length list of items chosen from the
sequence i.e. list, tuple, string or set.
Example:
from random import sample
print(sample(list1, 3))
Python tutorial
Output:
[2, 3, 5]
Output:
Your current time is: Wed Feb 9 17:41:26 2022
Get execution time of a program:
import time
initial1 = time.time()
i = 0
print("Using while loop")
while i < 10:
print("I am Hariom!")
i += 1
print("Time of while loop is: ", time.time() - initial1, "seconds")
initial2 = time.time()
Output:
Using while loop
Python tutorial
I am Hariom!
I am Hariom!
I am Hariom!
I am Hariom!
I am Hariom!
I am Hariom!
I am Hariom!
I am Hariom!
I am Hariom!
I am Hariom!
Time of while loop is: 0.0 seconds
I am Hariom!
I am Hariom!
I am Hariom!
I am Hariom!
I am Hariom!
Time of for loop is: 0.0 seconds
sleep(sec) :- This method is used to halt the program
execution for the time specified in the arguments.
Example:
import time
Output:
Enter a number: 5
5 X 1 = 5
5 X 2 = 10
5 X 3 = 15
5 X 4 = 20
5 X 5 = 25
Python tutorial
5 X 6 = 30
5 X 7 = 35
5 X 8 = 40
5 X 9 = 45
5 X 10 = 50
ctime(sec) :- This function returns a 24 character time
string but takes seconds as argument and computes time till
mentioned seconds. If no argument is passed, time is
calculated till present.
Example:
import time
print(time.ctime())
Output:
Wed Feb 9 17:53:08 2022
Localtime():
t converts number of seconds to local time. If secs is not provided or None, the current time as returned by
time() is used.
Example:
import time
print(time.localtime())
Output:
time.struct_time(tm_year=2022, tm_mon=2, tm_mday=9,
tm_hour=18, tm_min=2, tm_sec=2, tm_wday=2, tm_yday=40,
Python tutorial
tm_isdst=0)
time.time():
Pythom time method time() returns the time as a floating point number expressed in seconds since the epoch,
in UTC.
Example:
import time
print(time.time())
Output:
1644410136.2033668
To work with dates as date objects, we have to import the datetime module into the
python source code.
Consider the following example to get the datetime object representation for the current
time.
Example
1. import datetime
2. #returns the current datetime object
3. print(datetime.datetime.now())
Output:
2020-04-04 13:18:35.252578
Output:
2022-02-09
Get Today’s Year, Month, and Date
We can get the year, month, and date attributes from the date
object using the year, month and date attribute of the date class.
Example:
from datetime import date
Output:
Current year: 2022
Current month: 2
Current day: 9
Strftime() method:
Python tutorial
Output:
Current Month name short version: Feb
Current Month name full version: February
Current Month as a number: 02
Python tutorial
Example:
import calendar
print(calendar.month(2020, 3))
Output:
March 2020
Mo Tu We Th Fr Sa Su
1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31
Example 1:
import calendar
#printing the calendar of the year 2019
a = calendar.prcal(2020)
Output:
Example 2:
import calendar
# Printing the calendar of the year 2018
print("The calendar of 2018 is: ", calendar.calendar(2018))
Output:
Python tutorial
Python tutorial
Python Virtual Environment
Introduction
A virtual environment is a tool that helps to keep dependencies
required by different projects separate by creating isolated
python virtual environments for them. This is one of the most
important tools that most of the Python developers use.
Why do we need a virtual environment?
Imagine a scenario where you are working on two web based
python projects and one of them uses a Django 1.9 and the
other uses Django 1.10 and so on. In such situations virtual
environment can be really useful to maintain dependencies of
both the projects.
When and where to use a virtual environment?
By default, every project on your system will use these same
directories to store and retrieve site packages (third party
libraries). How does this matter? Now, in the above example of
two projects, you have two versions of Django. This is a real
problem for Python since it can’t differentiate between versions
in the “site-packages” directory. So both v1.9 and v1.10 would
reside in the same directory with the same name. This is where
virtual environments come into play. To solve this problem, we
just need to create two separate virtual environments for both
the projects.The great thing about this is that there are no limits
to the number of environments you can have since they’re just
directories containing a few scripts.
Virtual Environment should be used whenever you work on any
Python tutorial
time you work on the project. This can be done using the
following command:
(har) PS A:\Python Tutorial\virtual_enviroment> .\
my_name\Scripts\activate
Now you can create requirements.txt for the information
of all packages of python which you are using in your
project so that you can use this requirements.txt file for
install all packages so that there will be no problem
creates in other version of python.
For creating requirements.txt file type the following
command:
PS A:\Python Tutorial\virtual_enviroment> pip freeze >
requirements.txt
Now you can install all the packages which are available
in requirements.txt file.
For install all the packages at once, type the following
commands:
PS A:\Python Tutorial\virtual_enviroment> pip install -r
.\requirements.txt
Now it will install all packages of python.
Once you are done with the work, you can deactivate
the virtual environment by the following command:
Python tutorial
(virtualenv_name)$ deactivate
The next() method of the iterator returned by enumerate() returns a tuple and the values
obtained from iterating over a sequence.
Example:
result = enumerate([1,2,3])
# Displaying result
print(result)
print(list(result))
Output:
Example 2:
Here, we are passing the start index as 10. So, the enumerate will start from 10 to till the
elements present in the sequence.
Output:
(10, 1)
(11, 2)
(12, 3)
Example:
# printing the tuples in object directly
for ele in enumerate(l1):
print(ele)
print()
# changing index and printing separately
for count, ele in enumerate(l1, 100):
print(count, ele)
Output:
(0, 'eat')
(1, 'sleep')
(2, 'repeat')
100 eat
101 sleep
102 repeat
Python tutorial
0
eat
1
sleep
2
repeat
When we write a certain module name along with the import keyword, it will start
searching for a file with that name having an extension .py. After finding the file, it will
import it into our program, which means that it will permit our program to use the
functions of the certain module we imported. We can import a module named “sys” to
see the path that our import statement takes while searching for a module.
import sys
print( sys.path)
sys.path prints out a list of directories. When we tell Python to import something, then it
looks in each of the listed locations in order.
NOTE: When we give our file a name same as the name of a module, then
instead of importing the original module, the system will import our created
file because it starts its search for the file from the directory where the file
we are working on exists. So, we will not be able to use the functions of the
original file. So, we don’t use our file name same as python module name.
Python tutorial
The first one is to import using an object. For this, we usually import the whole
module by using a simple import statement. When we use only the import keyword,
we will import the resource directly, like this:
import sklearn
When we use the second syntax, we will import the resource from another package
or module. Here is an example:
Disadvantages:
One of the major disadvantages of the flexibility provided by a python in the case of
modules is that they can be easily modified and overridden. Along with disrupting the
functionality of the program, it also poses a major security risk.
#tutmain1.py
print("__name__ in tutmain1.py is set to"+__name__)
Output:
#tutmain2.py
import tutmain1
Python tutorial
Output:
if __name__ == “__main__:
when we import one file to another, along with the functions and variables,
we also import all the print statements and other such data that we do not
require. In such cases, we insert all the data of the module that we do not
want others to import into the main, and thus it can only be executed by the
file containing the main only.
The syntax is :
if__name__=="__main__":
#Logic Statement
Using the main in our file, we can restrict some data from
exporting to other files when imported.
We can restrict the unnecessary data, thus making the
output cleaner and more readable.
We can choose what others may import or what they may
not while using our module.
Example:
Let’s we have a given python file:
def printhar():
return f"This is a string!"
print(printhar())
addition = add(5, 6)
print(addition)
Output:
The name is __main__
This is a string!
11
Now we will import this file code in other file:
import file1
a = file1.add(10, 20)
print(a)
Output:
Python tutorial
list1 = ['1','2','3','4']
s = "-"
Output:
Python tutorial
1-2-3-4
Example 2: Joining with an empty string
list1 = ['H','a','r','i', 'o', ‘m’]
print("".join(list1))
Output:
Hariom
Example 3:
1. # Variable declaration
2. str = "->" # string
3. list = {'Java','C#','Python'} # iterable
4. # Calling function
5. str2 = str.join(list)
6. # Displaying result
7. print(str2)
Output:
Java->Python->C#
map() function:
Example 1:
def function(a):
return a*a
x = map(function, (1,2,3,4)) #x is the map object
print(x)
print(set(x))
OUTPUT
{1, 4, 9, 16}
Example 2:
numbers = ["43", "98", "26", "98", "13", "6", "3", "76", "58"]
print("Given list is: ", numbers)
numbers = list(map(int, numbers))
numbers[3] = numbers[3] + 2
print("Now Value of numbers[3] is: ", numbers[3])
lst = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]
square = list(map(lambda x: x*x, lst))
print("Squares are: ", square)
Output:
Given list is: ['43', '98', '26', '98', '13', '6', '3', '76', '58']
Now Value of numbers[3] is: 100
Squares are: [1, 4, 9, 16, 25, 36, 49, 64, 81, 100, 121, 144, 169,
196, 225, 256, 289, 324, 361, 400]
Cubes are: [1, 8, 27, 64, 125, 216, 343, 512, 729, 1000, 1331,
1728, 2197, 2744, 3375, 4096, 4913, 5832, 6859, 8000]
Python tutorial
filter() function:
The filter() function is used to generate an output list of values that return true
when the function is called. It has the following syntax:
Example:
list_1 = [12, 45, 98, 76, 1, 2, 3, 1, 3, 5, 4, 6, 7, 8, 10, 98, 534, 76, 435]
def is_Greater_10(num):
return num>10
def is_Loewr_10(num):
return num<10
Output:
Numbers greater tha 10: [12, 45, 98, 76, 98, 534, 76, 435]
Numbers lower than 10: [1, 2, 3, 1, 3, 5, 4, 6, 7, 8]
The reduce() function:
Example:
from functools import reduce
list1 = [1, 2, 3, 4, 5]
# Iterative way
num = 0
for i in list1:
num = num + i
print(num)
Output:
15
Total sum of list is: 15
Total product of list is: 120
Python tutorial
Python Decorator
Decorators are one of the most helpful and powerful tools of Python. These are used to
modify the behavior of the function. Decorators provide the flexibility to wrap another
function to expand the working of wrapped function, without permanently modifying it.
In Decorators, functions are passed as an argument into another function and then called inside the
wrapper function.
It is also called meta programming where a part of the program attempts to change
another part of program at compile time.
Example:
def dec1(func1):
def Now_Execute():
print("Executing Now")
func1()
print("Executed")
return Now_Execute
def name_1():
print("My name is Hariom Mewada")
name_1 = dec1(name_1)
name_1()
name_2()
Output:
Executing Now
My name is Hariom Mewada
Executed
Python tutorial
Syntax
1. class ClassName:
2. <statement-1>
3. .
4. .
5. <statement-N>
Object
The object is an entity that has state and behavior. It may be any real-world object like
the mouse, keyboard, chair, table, pen, etc.
Everything in Python is an object, and almost everything has attributes and methods. All
functions have a built-in attribute __doc__, which returns the docstring defined in the
function source code.
When we define a class, it needs to create an object to allocate the memory. Consider
the following example.
Example:
1. class car:
2. def __init__(self,modelname, year):
3. self.modelname = modelname
4. self.year = year
5. def display(self):
6. print(self.modelname,self.year)
7.
8. c1 = car("Toyota", 2016)
9. c1.display()
Python tutorial
Output:
Toyota 2016
In the above example, we have created the class named car, and it has two attributes
modelname and year. We have created a c1 object to access the class attribute. The c1
object will allocate memory for these values. We will learn more about class and object in
the next tutorial.
Method
The method is a function that is associated with an object. In Python, a method is not
unique to class instances. Any object type can have methods.
Inheritance
Inheritance is the most important aspect of object-oriented programming, which
simulates the real-world concept of inheritance. It specifies that the child object acquires
all the properties and behaviors of the parent object.
By using inheritance, we can create a class which uses all the properties and behavior of
another class. The new class is known as a derived class or child class, and the one
whose properties are acquired is known as a base class or parent class.
Polymorphism
Polymorphism contains two words "poly" and "morphs". Poly means many, and morph
means shape. By polymorphism, we understand that one task can be performed in
different ways. For example - you have a class animal, and all animals speak. But they
speak differently. Here, the "speak" behavior is polymorphic in a sense and depends on
the animal. So, the abstract "animal" concept does not actually "speak", but specific
animals (like dogs and cats) have a concrete implementation of the action "speak".
Encapsulation
Encapsulation is also an essential aspect of object-oriented programming. It is used to
restrict access to methods and variables. In encapsulation, code and data are wrapped
together within a single unit from being modified by accident.
Data Abstraction
Data abstraction and encapsulation both are often used as synonyms. Both are nearly
Python tutorial
Abstraction is used to hide internal details and show only functionalities. Abstracting
something means to give names to things so that the name captures the core of what a
function or a whole program does.
3. It simulates the real world entity. So It doesn't simulate the real world. It
real-world problems can be easily works on step by step instructions
solved through oops. divided into small parts called
functions.
Syntax
1. class ClassName:
Python tutorial
2. #statement_suite
Example
1. class Employee:
2. id = 10
3. name = "Devansh"
4. def display (self):
5. print(self.id,self.name)
Here, the self is used as a reference variable, which refers to the current class object. It
is always the first argument in the function definition. However, using self is optional in
the function call.
The self-parameter
The self-parameter refers to the current instance of the class and accesses the class
variables. We can use anything instead of self, but it must be the first parameter of any
function which belongs to the class.
1. <object-name> = <class-name>(<arguments>)
The following example creates the instance of the class Employee defined in the above
example.
Example 1:
1. class Employee:
2. id = 10
3. name = "John"
4. def display (self):
5. print("ID: %d \nName: %s"%(self.id,self.name))
6. # Creating a emp instance of Employee class
7. emp = Employee()
Python tutorial
8. emp.display()
Output:
ID: 10
Name: John
Example 2:
class Employee:
no_of_Leaves = 10
hariom = Employee()
Abhishek = Employee()
hariom.salary = 2500000
hariom.name = "Hariom"
hariom.role = "Software Engineer"
Abhishek.salary = 300000
Abhishek.name = "Abhishek"
Abhishek.role = "Product Manager"
print(Employee.no_of_Leaves)
print(hariom.no_of_Leaves)
print(Abhishek.no_of_Leaves)
hariom.no_of_Leaves = 12
print(hariom.__dict__)
print(Abhishek.__dict__)
print(Employee.no_of_Leaves)
Output:
10
10
10
{'salary': 2500000, 'name': 'Hariom', 'role': 'Software Engineer',
'no_of_Leaves': 12}
{'salary': 300000, 'name': 'Abhishek', 'role': 'Product Manager'}
10
Note: By using the __dict__ attribute on an object of a class
Python tutorial
Example
1. class Employee:
2. id = 10
3. name = "John"
4.
5. def display(self):
6. print("ID: %d \nName: %s" % (self.id, self.name))
7. # Creating a emp instance of Employee class
8.
9. emp = Employee()
10.
11. # Deleting the property of object
12. del emp.id
13. # Deleting the object itself
14. del emp
15. emp.display()
It will through the Attribute error because we have deleted the object emp.
hariom.salary = 2500000
hariom.name = "Hariom"
hariom.role = "Software Engineer"
Abhishek.salary = 300000
Abhishek.name = "Abhishek"
Abhishek.role = "Product Manager"
print(hariom.Print_Details())
print(Abhishek.Print_Details())
Output:
Name is Hariom, salary is 2500000 and role is Software
Engineer
Name is Abhishek, salary is 300000 and role is Product
Manager
Python Constructor
A constructor is a special type of method (function) which is used to initialize the instance
members of the class.
In C++ or Java, the constructor has the same name as its class, but it treats constructor
differently in Python. It is used to create an object.
1. Parameterized Constructor
2. Non-parameterized Constructor
Constructor definition is executed when we create the object of this class. Constructors
also verify that there are enough resources for the object to perform any start-up task.
We can pass any number of arguments at the time of creating the class object,
Python tutorial
depending upon the __init__() definition. It is mostly used to initialize the class attributes.
Every class must have a constructor, even if it simply relies on the default constructor.
Example
class Employee:
def __init__(self, Name, Role, Salary):
self.name = Name
self.role = Role
self.salary = Salary
Output:
Name is Hariom, Role is Software developer and Salary is
10000000
Python Non-Parameterized Constructor
The non-parameterized constructor uses when we do not want to manipulate the value or
the constructor that has only self as an argument. Consider the following example.
Example
1. class Student:
2. # Constructor - non parameterized
3. def __init__(self):
4. print("This is non parametrized constructor")
5. def show(self,name):
6. print("Hello",name)
7. student = Student()
8. student.show("John")
Example
1. class Student:
2. # Constructor - parameterized
3. def __init__(self, name):
4. print("This is parametrized constructor")
5. self.name = name
6. def show(self):
7. print("Hello",self.name)
8. student = Student("John")
9. student.show()
Output:
Example
1. class Student:
2. roll_num = 101
3. name = "Joseph"
4.
5. def display(self):
6. print(self.roll_num,self.name)
7.
8. st = Student()
9. st.display()
Output:
101 Joseph
Python tutorial
Example
1. class Student:
2. def __init__(self):
3. print("The First Constructor")
4. def __init__(self):
5. print("The second contructor")
6.
7. st = Student()
Output:
In the above code, the object st called the second constructor whereas both have the
same configuration. The first method is not accessible by the st object. Internally, the
object of the class will always call the last constructor if the class has multiple
constructors.
SN Attribute Description
Example
class Student:
def __init__(self,name,id,age):
self.name = name
self.id = id
self.age = age
def display_details(self):
print("Name:%s, ID:%d, age:%d" %(self.name,self.id, self.age))
s = Student("John",101,22)
s.display_details()
print(s.__doc__)
print(s.__dict__)
print(s.__module__)
Output:
Name:John, ID:101, age:22
None
{'name': 'John', 'id': 101, 'age': 22}
__main__
we cannot change the value of a variable defined in the class from outside
using an object. Instead, if we try that, a new instance variable will be
created for the class having the value we assigned. But no change will occur
in the original value of the variable.
Python tutorial
@classmethod Characteristics
Declares a class method.
The first parameter must be cls, which can be used to access class
attributes.
The class method can only access the class attributes but not the instance
attributes.
The class method can be called using ClassName.MethodName() and also using
object.
It can return an object of the class.
@classmethod
def change_policy(cls, new_leaves, new_time):
cls.no_of_leaves = new_leaves
cls.Working_time = new_time
Hariom = Employee()
Ansh = Employee()
Hariom.change_policy(15, 6)
print("No. of leaves = ", Ansh.no_of_leaves)
print("Woking time = ", Ansh.Working_time)
Output:
No. of leaves = 15
Woking time = 6
@classmethod
def from_slash(cls, string):
# params = string.split("/")
# return cls(params[0], params[1], params[2])
return cls(*string.split("/")) # This is one liner of above code
Output:
Details of Employee: Name is Raj Rajput , salary is 35000 and
role is Manager
Details of Employee: Name is Hariom Rajput , salary is 85000
and role is Instructor
If we want multiple and independent "constructors", we can use class
methods. They are usually called factory methods. It does not invoke the
default constructor __init__.In the above example, we split the string based
on the "/" operator. We first create a class method as a constructor that
takes the string and split it based on the specified operator. For this
purpose, we use a split() function, which takes the separator as a parameter.
This alternative constructor approach is useful when we have to deal with
files containing string data separated by a separator.
split():
it takes a separator as a parameter. If we do not provide any,
then the default separator is any whitespace it encounters. Else
we can provide any separator to it such as full stop, hash, dash,
colon, etc. After separating the string into parts, the split()
function stores it into a list in a sequence. For example:
t = text.split()
print(t)
@staticmethod Characteristics
Declares a static method in the class.
It cannot have cls or self parameter.
The static method cannot access the class attributes or the instance
attributes.
The static method can be called using ClassName.MethodName() and also
using object.MethodName().
It can return an object of the class.
Example 1:
class Dates:
def __init__(self, date):
self.date = date
def getDate(self):
Python tutorial
return self.date
@staticmethod
def toDashDate(date):
return date.replace("/", "-")
date = Dates("15-12-2016")
dateFromDB = "15/12/2016"
dateWithDash = Dates.toDashDate(dateFromDB)
if(date.getDate() == dateWithDash):
print("Equal")
else:
print("Unequal")
Output
Equal
Example 2:
class Employee:
@staticmethod
def print_Hello(string):
print("Hello " + string)
Employee.print_Hello("Hariom")
Aman = Employee()
Aman.print_Hello("Aman")
Output:
Hello Hariom
Hello Aman
Differences between Class Method and Static Method:
Python Inheritance
Inheritance is an important aspect of the object-oriented paradigm. Inheritance provides
code reusability to the program because we can use an existing class to create a new
class instead of creating it from scratch.
In inheritance, the child class acquires the properties and can access all the data
members and functions defined in the parent class. A child class can also provide its
specific implementation to the functions of the parent class. In this section of the tutorial,
we will discuss inheritance in detail.
In python, a derived class can inherit base class by just mentioning the base in the
bracket after the derived class name. Consider the following syntax to inherit a base
class into the derived class.
Python tutorial
Syntax
1. class derived-class(base class):
2. <class-suite>
A class can inherit multiple classes by mentioning all of them inside the bracket. Consider
the following syntax.
Syntax
1. class derive-class(<base class 1>, <base class 2>, ..... <base class n>):
2. <class - suite>
Example 1
1. class Animal:
2. def speak(self):
3. print("Animal Speaking")
4. #child class Dog inherits the base class Animal
5. class Dog(Animal):
6. def bark(self):
7. print("dog barking")
8. d = Dog()
9. d.bark()
10. d.speak()
Python tutorial
Output:
dog barking
Animal Speaking
Syntax
1. class Base1:
2. <class-suite>
3.
4. class Base2:
5. <class-suite>
6. .
7. .
8. .
9. class BaseN:
10. <class-suite>
11.
12. class Derived(Base1, Base2, ...... BaseN):
13. <class-suite>
Python tutorial
Example 1:
1. class Calculation1:
2. def Summation(self,a,b):
3. return a+b;
4. class Calculation2:
5. def Multiplication(self,a,b):
6. return a*b;
7. class Derived(Calculation1,Calculation2):
8. def Divide(self,a,b):
9. return a/b;
10. d = Derived()
11. print(d.Summation(10,20))
12. print(d.Multiplication(10,20))
13. print(d.Divide(10,20))
Output:
30
200
0.5
Example 2:
class Student: # Class 1
def __init__(self, name, standard, roll_no, result):
self.name = name
self.std = standard
self.Roll_no = roll_no
self.result = result
def Print_details(self):
return f"Student name is {self.name}, Standard is {self.std}, Roll number is {self.Roll_no}
and Result is {self.result}"
def Print_details(self):
return f"Student game is {self.game} and Position is {self.position}"
Output:
Student name is hariom, Standard is 12th, Roll number is
1005 and Result is 90
Cricket
State Champian
Language : Python
Python Multi-Level inheritance
Multi-Level inheritance is possible in python like other object-oriented languages. Multi-
level inheritance is archived when a derived class inherits another derived class. There is
no limit on the number of levels up to which, the multi-level inheritance is archived in
python.
Python tutorial
Syntax
1. class class1:
2. <class-suite>
3. class class2(class1):
4. <class suite>
5. class class3(class2):
6. <class suite>
7. .
8. .
Example
1. class Animal:
2. def speak(self):
3. print("Animal Speaking")
4. #The child class Dog inherits the base class Animal
5. class Dog(Animal):
6. def bark(self):
7. print("dog barking")
8. #The child class Dogchild inherits another child class Dog
9. class DogChild(Dog):
10. def eat(self):
11. print("Eating bread...")
12. d = DogChild()
13. d.bark()
14. d.speak()
15. d.eat()
Output:
dog barking
Animal Speaking
Eating bread...
Python tutorial
Example
1. class Calculation1:
2. def Summation(self,a,b):
3. return a+b;
4. class Calculation2:
5. def Multiplication(self,a,b):
6. return a*b;
7. class Derived(Calculation1,Calculation2):
8. def Divide(self,a,b):
9. return a/b;
10. d = Derived()
11. print(issubclass(Derived,Calculation2))
12. print(issubclass(Calculation1,Calculation2))
Output:
True
False
Example
1. class Calculation1:
Python tutorial
2. def Summation(self,a,b):
3. return a+b;
4. class Calculation2:
5. def Multiplication(self,a,b):
6. return a*b;
7. class Derived(Calculation1,Calculation2):
8. def Divide(self,a,b):
9. return a/b;
10. d = Derived()
11. print(isinstance(d,Derived))
Output:
True
Method Overriding
We can provide some specific implementation of the parent class method in our child
class. When the parent class method is defined in the child class with some specific
implementation, then the concept is called method overriding. We may need to perform
method overriding in the scenario where the different definition of a parent class method
is needed in the child class.
Example
1. class Animal:
2. def speak(self):
3. print("speaking")
4. class Dog(Animal):
5. def speak(self):
6. print("Barking")
7. d = Dog()
8. d.speak()
Output:
Barking
Python tutorial
# constructor
def __init__(self, name, age):
# public data members
self.Name = name
self.Age = age
Output:
Name: R2J
Age: 20
# super class
class Student:
# protected data members
_My_Self = "Hariom Singh Rajput"
_name = None
_roll = None
_branch = None
# constructor
Python tutorial
def __init__(self, name, roll, branch):
self._name = name
self._roll = roll
self._branch = branch
# derived class
class Juniar(Student):
# constructor
def __init__(self, name, roll, branch):
Student.__init__(self, name, roll, branch)
Output:
Name: R2J
Roll: 1706256
Branch: Information Technology
Hariom Singh Rajput
class Geek:
# private members
__MyName = "hariom Singh Rajput" # Private member
__name = None
__roll = None
__branch = None
# constructor
def __init__(self, name, roll, branch):
self.__name = name
self.__roll = roll
self.__branch = branch
# creating object
# Name mangling
print(obj._Geek__name)
print(obj._Geek__roll)
print("My name is: ", obj._Geek__MyName)
Output:
Roll: 1706256
Branch: Information Technology
R2J
Python tutorial
1706256
My name is: hariom Singh Rajput
Name Mangling
A process in which any given identifier with one trailing underscore and two leading
underscores is textually replaced with the __ClassName__Identifier is known as Name
mangling. In __ClassName__Identifier name, ClassName is the name of current class
where identifier is present.
Example:
class My_Data:
# Private Access Specifier
__Name = "Hariom"
__Semester = 3
__Collage = "SISTech"
__GPA = 8.5
# Protected Access Specifier
_Course = "B.Tech"
Student = My_Data()
# print("My name is: ", Student.__Name) # This will give an error because we can't use private
specifier Outside the class
# We will use Name Mangling for using Private data of the class
print("My name is: ", Student._My_Data__Name)
print("Semester: ", Student._My_Data__Semester)
print("Collage: ", Student._My_Data__Collage)
print("GPA: ", Student._My_Data__GPA)
Output:
My name is: Hariom
Python tutorial
Semester: 3
Collage: SISTech
GPA: 8.5
Course: B.Tech
Encapsulation in Python
Encapsulation is one of the fundamental concepts in object-
oriented programming (OOP). It describes the idea of wrapping
data and the methods that work on data within one unit. This
puts restrictions on accessing variables and methods directly
and can prevent the accidental modification of data. To prevent
accidental change, an object’s variable can only be changed by
an object’s method. Those types of variables are known
as private
variable
A class is an example of encapsulation as it encapsulates all the
data that is member functions, variables, etc.
Python tutorial
Protected members
Protected members (in C++ and JAVA) are those members of
the class that cannot be accessed outside the class but can be
accessed from within the class and its subclasses. To
accomplish this in Python, just follow the convention by
prefixing the name of the member by a single underscore “_”.
Although the protected variable can be accessed out of the
class as well as in the derived class(modified too in derived
class), it is customary(convention not a rule) to not access the
protected out the class body.
Example:
# Python program to
# demonstrate protected members
# Protected member
self._a = 2
# Calling constructor of
# Base class
Base.__init__(self)
print("Calling protected member of base class: ",
self._a)
obj1 = Derived()
obj2 = Base()
Output:
Calling protected member of base class: 2
Calling modified protected member outside class: 3
Accessing protedted member of obj1: 3
Accessing protedted member of obj2: 2
Private members
Private members are similar to protected members, the
difference is that the class members declared private should
neither be accessed outside the class nor by any base class. In
Python, there is no existence of Private instance variables that
cannot be accessed except inside a class.
However, to define a private member prefix the member name
with double underscore “__”.
Example:
# Python program to
# demonstrate private members
Python tutorial
# Creating a Base class
class Base:
def __init__(self):
self.a = "Wellcome"
self.__c = "Wellcome"
# Calling constructor of
# Base class
Base.__init__(self)
print("Calling private member of base class: ")
print(self.__c)
# Driver code
obj1 = Base()
print(obj1.a)
Output:
Output:
Wellcome
Traceback (most recent call last):
File "/home/f4905b43bfcf29567e360c709d3c52bd.py", line 25,
in <module>
Python tutorial
print(obj1.c)
AttributeError: 'Base' object has no attribute 'c'
Abstraction in Python
Abstraction is used to hide the internal functionality of the function from the users. The
users only interact with the basic implementation of the function, but inner working is
hidden. User is familiar with that "what function does" but they don't know "how it
does."
In simple words, we all use the smartphone and very much familiar with its functions
such as camera, voice-recorder, call-dialing, etc., but we don't know how these
operations are happening in the background. Let's take another example - When we use
the TV remote to increase the volume. We don't know how pressing a key increases the
volume of the TV. We only know to press the "+" button to increase the volume.
And
A class that consists of one or more abstract method is called the abstract class. Abstract
methods do not contain their implementation. Abstract class can be inherited by the
subclass and abstract method gets its definition in the subclass. Abstraction classes are
meant to be the blueprint of the other class. An abstract class can be useful when we are
designing large functions. An abstract class is also helpful to provide the standard
interface for different implementations of components. Python provides the abc module
to use the abstraction in the Python program. Let's see the following syntax.
Syntax
1. Abstract methods are defined in the abstract class. They mostly do not have the
body, but it is possible to implement abstract methods in the abstract class. Any
subclass deriving from such an abstract class still needs to provide an
implementation for that abstract method.
2. An abstract class can have both abstract methods as well as concrete methods.
3. The abstract class works as a template for other classes.
4. Using the abstract class, we can define a structure without properly implementing
every method.
5. It is not possible to create objects of an abstract class because Abstract class
cannot be instantiated.
6. An error will occur if the abstract method has not been implemented in the derived
class.
Example 1:
class Shape(ABC):
@abstractmethod
def printarea(self): # Force for making printarea function in all child classes
return 0
class Rectangle(Shape):
type = "Rectangle"
sides = 4
def __init__(self):
self.length = 6
self.breadth = 9
def printarea(self):
return self.length * self.breadth
Python tutorial
rect1 = Rectangle()
print(rect1.printarea())
Output:
54
Example 2:
class Tesla(Car):
def mileage(self):
print("The mileage is 30kmph")
class Suzuki(Car):
def mileage(self):
print("The mileage is 25kmph ")
class Duster(Car):
def mileage(self):
print("The mileage is 24kmph ")
class Renault(Car):
def mileage(self):
print("The mileage is 27kmph ")
pass
# Driver code
t= Tesla ()
t.mileage()
r = Renault()
r.mileage()
s = Suzuki()
s.mileage()
d = Duster()
d.mileage()
Output:
If we will not define mileage method inside the child class of Car
then it will throw an error when we create a object of this class.
Python tutorial
Example:
# Python program demonstrate
# abstract base class work
from abc import ABC, abstractmethod
class Car(ABC):
@abstractmethod
def mileage(self):
pass
class Tesla(Car):
def mileage(self):
print("The mileage is 30kmph")
class Suzuki(Car):
def mileage(self):
print("The mileage is 25kmph ")
class Duster(Car):
def mileage(self):
print("The mileage is 24kmph ")
class Renault(Car):
pass
# Driver code
t= Tesla ()
t.mileage()
r = Renault()
s = Suzuki()
s.mileage()
d = Duster()
d.mileage()
Output:
The mileage is 30kmph
Traceback (most recent call last):
File "A:\Python Tutorial\15.Python Object Oriented
Programming\20_Abstract_method.py", line 26, in <module>
r = Renault()
TypeError: Can't instantiate abstract class Renault with abstract
method mileage
Python tutorial
Points to Remember
Below are the points which we should remember about the abstract base class in Python.
o An Abstract class can contain the both method normal and abstract method.
o An Abstract cannot be instantiated; we cannot create objects for the abstract class.
Polymorphism in Python
What is Polymorphism: The word polymorphism means having
many forms. In programming, polymorphism means the same
function name (but different signatures) being used for different
types.
Polymorphism means multiple forms. In python we can find the same operator or function taking multiple forms.
It also useful in creating different classes which will have class methods with same name. That helps in re using
a lot of code and decreases code complexity.
Output:
5
3
Python tutorial
# Driver code
print(add(2, 3))
print(add(2, 3, 4))
Output:
5
9
Polymorphism with class methods:
class India():
def capital(self):
print("New Delhi is the capital of India.")
def language(self):
print("Hindi is the most widely spoken language of India.")
def type(self):
print("India is a developing country.")
class USA():
def capital(self):
print("Washington, D.C. is the capital of USA.")
def language(self):
print("English is the primary language of USA.")
def type(self):
print("USA is a developed country.")
obj_ind = India()
obj_usa = USA()
for country in (obj_ind, obj_usa):
Python tutorial
country.capital()
country.language()
country.type()
Output:
New Delhi is the capital of India.
Hindi is the most widely spoken language of India.
India is a developing country.
Washington, D.C. is the capital of USA.
English is the primary language of USA.
USA is a developed country.
Polymorphism with Inheritance:
class Bird:
def intro(self):
print("There are many types of birds.")
def flight(self):
print("Most of the birds can fly but some cannot.")
class sparrow(Bird):
def flight(self):
print("Sparrows can fly.")
class ostrich(Bird):
def flight(self):
print("Ostriches cannot fly.")
obj_bird = Bird()
obj_spr = sparrow()
obj_ost = ostrich()
obj_bird.intro()
obj_bird.flight()
Python tutorial
obj_spr.intro()
obj_spr.flight()
obj_ost.intro()
obj_ost.flight()
Output:
There are many types of birds.
Most of the birds can fly but some cannot.
There are many types of birds.
Sparrows can fly.
There are many types of birds.
Ostriches cannot fly.
def __init__(self):
Python tutorial
# Now this instance variable will not print because this constructor has been override
self.classVar1 = "I am a variable of class A inside The Constructor" # First Find here
class B(A):
classVar1 = "I am a variable of class B" # Second Find here
a = A()
b = B()
print(b.classVar1)
Output:
I am a variable of class B
Using Super():
Python super() function provides us the facility to refer to the
parent class explicitly. It is basically useful where we have to call
superclass functions. It returns the proxy object that allows us to
refer parent class by ‘super’.
Example 1: Use super before declaring variable
class A:
classVar1 = "I am a variable of class A" # Third Find here
def __init__(self):
# Now this instance variable will print because we used super method
self.classVar1 = "I am a variable of class A inside The Constructor" # First Find here
class B(A):
classVar1 = "I am a variable of class B" # Second Find here
a = A()
b = B()
print(b.classVar1)
Output:
Python tutorial
def __init__(self):
# Now this instance variable will print because we used super method
self.classVar1 = "I am a variable of class A inside The Constructor" # First Find here
class B(A):
classVar1 = "I am a variable of class B" # Second Find here
a = A()
b = B()
print(b.classVar1)
Output:
I am a variable of class A inside The Constructor
# Driver Code
if __name__ == '__main__':
# object creation
string1 = String('Hello')
Output :
<__main__.String object at 0x7fe992215390>
The above snippet of code prints only the memory address of
the string object. Let’s add a __repr__ method to represent our
object.
__repr__() method:
# declare our own string class
class String:
# Driver Code
if __name__ == '__main__':
# object creation
string1 = String('Hello')
Output :
Object: Hello
__str__() method:
Another useful magic method is __str__(). It is overridden to return a printable
string representation of any user defined class.
Example:
class Employee:
def __init__(self, Name, Role, Salary):
self.name = Name
self.role = Role
self.salary = Salary
def __str__(self):
return f"Name is {self.name}, salary is {self.salary} and role is {self.role}"
Example:
class Employee:
def __init__(self, Name, Role, Salary):
self.name = Name
self.role = Role
self.salary = Salary
def Print_Details(self):
return f"Name is {self.name}, salary is {self.salary} and role is {self.role}"
def __repr__(self):
return f"Employee('{self.name}', '{self.role}', {self.salary})"
def __str__(self):
return f"Name is {self.name}, salary is {self.salary} and role is {self.role}"
def __len__(self):
return len(self.name)
print(emp1+emp2)
print(emp1/emp2)
Python tutorial
print(emp1)
print(repr(emp1))
print(len(emp2))
Output:
600000
0.2
This table shows how abstract operations correspond to operator symbols in the Python syntax and
the functions in the operator module.
Addition a + b add(a, b)
Division a // b floordiv(a, b)
Bitwise Or a | b or_(a, b)
Python tutorial
Exponentiation a ** b pow(a, b)
Identity a is b is_(a, b)
Modulo a % b mod(a, b)
Multiplication a * b mul(a, b)
Subtraction a - b sub(a, b)
Difference a != b ne(a, b)
Syntax:
@property
#def getter method
@function_name.setter
#def function
# Deleter method
@function_name.deleter
def Explain(self):
return f"This Employee is {self.fname} {self.lname}"
@property
# Getter method
def Email(self):
if self.fname == None and self.lname == None:
return f"Your Email is not set. Please set it using setter..."
return f"{self.fname}{self.lname}[email protected]"
@Email.setter
# Setter method
def Email(self, string):
print("Setting Now...")
names = string.split("@")[0]
self.fname = names.split(".")[0]
self.lname = names.split(".")[1]
@Email.deleter
# Deleter method
def Email(self):
print("\nYour Email has been deleted successfully!")
self.fname = None
self.lname = None
print()
emp1.Email = "[email protected]"
print("My newest email is: ", emp1.Email)
print("My first name : ", emp1.fname)
print("My last name : ", emp1.lname)
del emp1.Email
print(emp1.Email)
Python tutorial
Output:
My first name : Hariom
My last name : mewada
My old Email is: [email protected]
My new Email is: [email protected]
Setting Now...
My newest email is: [email protected]
My first name : Harionsingh
My last name : Rajput
def Explain(self):
return f"This Employee is {self.fname} {self.lname}"
@property
# Getter method
def Email(self):
if self.fname == None and self.lname == None:
return f"Your Email is not set. Please set it using setter..."
return f"{self.fname}{self.lname}[email protected]"
@Email.setter
# Setter method
def Email(self, string):
print("Setting Now...")
names = string.split("@")[0]
self.fname = names.split(".")[0]
self.lname = names.split(".")[1]
@Email.deleter
# Deleter method
Python tutorial
def Email(self):
print("\nYour Email has been deleted successfully!")
self.fname = None
self.lname = None
# Type
a = 5
b = [1, 2, 3, 4, 5]
print("\nObject Introspection using type method: ")
print("Type of string Hello is: ", type('Hello'))
print("Type of object of the class is: ", type(emp1))
print("Type of a is: ", type(a))
print("Type of b is: ", type(b))
# str
a = str(a)
b = str(b)
print("\nObject Introspection using str method: ")
print("After Typecasting type of a is: ", type(a))
print("After Typecasting type of b is: ", type(b))
# id
print("\nObject Introspection using id method: ")
print("Id of given string is: ", id('Well Come'))
print("Id of given string is: ", id('Well Come Back'))
print("Id of a is: ", id(a))
# dir
string = "Good Morning"
print("\nObject Introspection using dir method: ")
print("Information about given string is: ", dir(string))
print("Information about given object is: ", dir(emp1))
# import inspect
# print(inspect.getmembers())
Output:
Object Introspection using type method:
Type of string Hello is: <class 'str'>
Type of object of the class is: <class '__main__.Employee'>
Type of a is: <class 'int'>
Type of b is: <class 'list'>
Python tutorial
Example:
import inspect
class A:
def Cube(self, a):
return a * a * a
pass
def Sqrt(self,a):
return a*a
a = A()
# isclass
print(inspect.isclass(A))
# ismodule
print(inspect.ismodule(inspect))
# isfunction
print(inspect.isfunction(Sqrt))
print(inspect.isfunction(a.Cube))
# ismethod
print(inspect.ismethod(Sqrt))
print(inspect.ismethod(a.Cube))
Output:
Python tutorial
True
True
True
False
False
True
Example:
import inspect
import collections
from tkinter import *
class A:
pass
class B(A):
pass
class C(B):
pass
a = A()
root = Tk()
print("\nThe getmro() method of inspect module: \n", inspect.getmro(C))
print("\nThe getclasstree() method of inspect module: \n", inspect.getclasstree(inspect.getmro(C)))
print("\nThe getmembers() method of inspect module: \n", inspect.getmembers(a))
print("\nThe getsource() method of inspect module: \n", inspect.getsource(func))
print("\nThe getmodule() method of inspect module: \n", inspect.getmodule(collections))
print("\nThe getdoc() method of inspect module: \n", inspect.getdoc(root))
Output:
The getmro() method of inspect module:
(<class '__main__.C'>, <class '__main__.B'>, <class
'__main__.A'>, <class 'object'>)
Python tutorial
Generators in Python
Python Generators
What is Python Generator?
Python Generators are the functions that return the traversal object and used to create
iterators. It traverses the entire items at once. The generator can also be an expression
in which syntax is similar to the list comprehension in Python.
It is a lengthy process to create iterators. That's why the generator plays an essential role
in simplifying this process. If there is no value found in iteration, it
raises StopIteration exception.
Example:
def gen(n):
for i in range(n):
yield i
g = gen(100000000000000000000)
print(g)
name = "Hariom"
iter_name = iter(name)
print(iter_name.__next__())
print(iter_name.__next__())
print(iter_name.__next__())
print(iter_name.__next__())
print(iter_name.__next__())
print(iter_name.__next__())
print(iter_name.__next__())
Python tutorial
Output:
<generator object gen at 0x000002A3BAAA1EE0>
H
a
r
i
o
m
Traceback (most recent call last):
File "A:\Python Tutorial\14. Other Topics\
Generators_in_Python\1_Generator.py", line 16, in
<module>
print(iter_name.__next__())
StopIteration
def factorial(n):
fac = 1
for i in range(n):
fac = fac * (i+1)
yield fac
choice = int(input('''
___________Choose any option for continue____________
1. Febonnaci number
2. factorial
'''))
if choice == 1:
num = int(input("Enter any number: "))
print("The febonnaci sequence is as below: ")
for i in febonnaci(num):
print(i, end=" ")
elif choice == 2:
num = int(input("Enter any number: "))
Number = 1
for i in factorial(num):
print(f"Factorial of {Number} is : {i}")
Number += 1
else:
print("Invalid input!")
Factorial of 9 is : 362880
Factorial of 10 is : 3628800
Factorial of 11 is : 39916800
Factorial of 12 is : 479001600
Factorial of 13 is : 6227020800
Factorial of 14 is : 87178291200
Factorial of 15 is : 1307674368000
Factorial of 16 is : 20922789888000
Factorial of 17 is : 355687428096000
Factorial of 18 is : 6402373705728000
Factorial of 19 is : 121645100408832000
Factorial of 20 is : 2432902008176640000
Factorial of 21 is : 51090942171709440000
Factorial of 22 is : 1124000727777607680000
Factorial of 23 is : 25852016738884976640000
Factorial of 24 is : 620448401733239439360000
Factorial of 25 is : 15511210043330985984000000
2. Generator-Object : Generator functions return a generator
object. Generator objects are used either by calling the next
Python tutorial
# x is a generator object
x = simpleGeneratorFun()
Output:
1
2
3
Example 2:
def simpleGeneratorFun(n):
num = 1
for i in range(1, n+1):
yield i
def factorial(n):
fac = 1
for i in range(n):
fac = fac * (i+1)
yield fac
x = factorial(10)
y = simpleGeneratorFun(10)
print(f"Factorial of {y.__next__()} is: {x.__next__()} ")
print(f"Factorial of {y.__next__()} is: {x.__next__()} ")
print(f"Factorial of {y.__next__()} is: {x.__next__()} ")
print(f"Factorial of {y.__next__()} is: {x.__next__()} ")
Python tutorial
print(f"Factorial of {y.__next__()} is: {x.__next__()} ")
print(f"Factorial of {y.__next__()} is: {x.__next__()} ")
print(f"Factorial of {y.__next__()} is: {x.__next__()} ")
Output:
Factorial of 1 is: 1
Factorial of 2 is: 2
Factorial of 3 is: 6
Factorial of 4 is: 24
Factorial of 5 is: 120
Factorial of 6 is: 720
Factorial of 7 is: 5040
Once the function yields, the function is paused and the control is transferred to the
caller.
Local variables and their states are remembered between successive calls.
further calls.
Advantages of Generators
1. EASY TO IMPLEMENT
Generators are easy to implement as compared to the iterator. In iterator, we have to
implement __iter__() and __next__() function.
2. MEMORY EFFICIENT
Generators are memory efficient for a large number of sequences. The normal function
returns a sequence of the list which creates an entire sequence in memory before
returning the result, but the generator function calculates the value and pause their
execution. It resumes for successive call. An infinite sequence generator is a great
example of memory optimization. Let's discuss it in the below example by
using sys.getsizeof() function.
1. import sys
2. # List comprehension
3. nums_squared_list = [i * 2 for i in range(1000)]
4. print(sys.getsizeof("Memory in Bytes:"nums_squared_list))
5. # Generator Expression
6. nums_squared_gc = (i ** 2 for i in range(1000))
7. print(sys.getsizeof("Memory in Bytes:", nums_squared_gc))
Output:
We can observe from the above output that list comprehension is using 4508 bytes of memory,
whereas generator expression is using 56 bytes of memory. It means that generator objects are
much efficient than the list compression.
The generator can produce infinite items. Infinite sequences cannot be contained within
the memory and since generators produce only one item at a time, consider the following
example:
1. def infinite_sequence():
Python tutorial
2. num = 0
3. while True:
4. yield num
5. num += 1
6.
7. for i in infinite_sequence():
8. print(i)
Comprehensions in Python
Comprehensions in Python provide us with a short and concise
way to construct new sequences (such as lists, set, dictionary
etc.) using sequences which have been already defined. Python
supports the following 4 types of comprehensions:
List Comprehensions
Dictionary Comprehensions
Set Comprehensions
Generator Comprehensions
List Comprehensions:
List Comprehensions provide an elegant way to create new lists.
Example 1:
# Generate a list by using list Comprehension
l1 = [i for i in range(50)]
print(l1)
print(type(l1))
Output:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19,
Python tutorial
20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36,
37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49]
<class 'list'>
Output:
[5, 10, 15, 20, 25, 30, 35, 40, 45, 50, 55, 60, 65, 70, 75, 80, 85,
90, 95, 100]
Dictionary Comprehensions:
Extending the idea of list comprehensions, we can also create a
dictionary using dictionary comprehensions.
Example 1:
# Create a dictionary by using dictionary comprehension
Dict1 = {i : f"item {i} " for i in range(1, 6)}
print(Dict1)
Output:
{1: 'item 1 ', 2: 'item 2 ', 3: 'item 3 ', 4: 'item 4 ', 5: 'item 5 '}
{10: 'My_Item 10 ', 20: 'My_Item 20 ', 30: 'My_Item 30 ', 40:
'My_Item 40 ', 50: 'My_Item 50 '}
{'My_Item 10 ': 10, 'My_Item 20 ': 20, 'My_Item 30 ': 30,
'My_Item 40 ': 40, 'My_Item 50 ': 50}
Example 2: Using zip() function
state = ['Gujarat', 'Maharashtra', 'Rajasthan', 'Madhya Pradesh']
capital = ['Gandhinagar', 'Mumbai', 'Jaipur', 'Bhopal']
Output:
Output Dictionary using dictionary comprehensions: {'Gujarat':
'Gandhinagar', 'Maharashtra': 'Mumbai', 'Rajasthan': 'Jaipur',
'Madhya Pradesh': 'Bhopal'}
<class 'dict'>
Set Comprehensions:
Set comprehensions are pretty similar to list comprehensions.
The only difference between them is that set comprehensions
use curly brackets { }.
Example:
# Creating a set by using set comprehension
colors = {color for color in ["Red", "Blue", "Red", "Green", "Red", "Yellow", "Blue", "White",
"Black", "Orange", "Yellow"]}
Python tutorial
print(type(colors))
print("Set of colors: ", colors)
Example:
<class 'set'>
Set of colors: {'Blue', 'Red', 'Black', 'Green', 'Orange', 'White',
'Yellow'}
Generator Comprehensions:
Generator Comprehensions are very similar to list
comprehensions. One difference between them is that generator
comprehensions use circular brackets whereas list
comprehensions use square brackets. The major difference
between them is that generators don’t allocate memory for the
whole list. Instead, they generate each value one by one which
is why they are memory efficient.
Example:
# Creating generator by using comprehension
evens = (x**3 for x in range(1, 11) if x % 2 == 0)
print(type(evens))
print("Cube of Even numbers[1 - 10] : ")
for items in evens:
print(items, end=" ")
Output:
<class 'generator'>
Cube of Even numbers[1 - 10] :
8 64 216 512 1000
Whole types of Comprehensions:
Python tutorial
Example:
num = int(input("How many elements you want to add: "))
input_elements = input("Enter elements separated by space: ")
List = input_elements.split()
choice = input('''
Which type of Comprehension you want to create?
A. For List Comprehension
B. For Dictionary Comprehension
C. For Set Comprehension
D. For Generator Comprehension
-->
''')
if choice == 'A':
list1 = [a for a in List]
print(list1)
print(type(list1))
Output:
How many elements you want to add: 10
Enter elements separated by space: Red Blue Green Yellow
Red Purple White Red Yellow Orange
-->
C
{'Orange', 'Purple', 'Green', 'Blue', 'Yellow', 'Red', 'White'}
<class 'set'>
@ lru_cache(maxsize=3)
def Some_Work(n):
# Some tasks taking n seconds
time.sleep(n)
return n
if __name__ == '__main__':
print("Now running some work...")
Starting_time1 = time.time()
Some_Work(4)
Python tutorial
ending_time1 = time.time()
print("Time taken in execution --> ", ending_time1 - Starting_time1)
Output:
Now running some work...
Time taken in execution --> 4.005024194717407
Done! Calling again..
Time taken in execution --> 0.0
Called again!
Example 2:
from functools import lru_cache
import time
print("Time taken to execute the function without lru_cache is", end - begin)
begin = time.time()
Python tutorial
fib_with_cache(35)
end = time.time()
print("Time taken to execute the function with lru_cache is", end - begin)
Output:
Time taken to execute the function without lru_cache is
2.5713326930999756
Time taken to execute the function with lru_cache is 0.0
Python Coroutine
Coroutines are generalizations of subroutines. They are used for
cooperative multitasking where a process voluntarily yield (give
away) control periodically or when idle in order to enable
multiple applications to be run simultaneously.
In Python, coroutines are similar to generators but with few extra
methods and slight changes in how we use yield statements.
Generators produce data for iteration while coroutines can
also consume data.
whatever value we send to coroutine is captured and returned
by (yield) expression.
A value can be sent to the coroutine by send() method.
Example 1:
def searcher():
import time
# Assume that this is a 4 seconds time consuming task
book = "This is a book about python, and you can get all knowledge of python from basic to very
advance."
time.sleep(4)
Python tutorial
print("This is a python book description")
search = searcher()
next(search)
search.send("knowledge")
input("Press any key: ")
search.send("basic to very advance")
search.close()
input("Press any key: ")
search.send("This is a book")
Output:
This is a python book description
This text is available in the book!
Press any key:
This text is available in the book!
Press any key:
Traceback (most recent call last):
File "A:\Python Tutorial\14. Other Topics\
Coroutines_in_python\1_Coroutines.py", line 22, in <module>
search.send("This is a book")
StopIteration
Example 2:
def searcher():
import time
Python tutorial
# Assume that this is a 4 seconds time consuming task
time.sleep(4)
if __name__ == '__main__':
search = searcher()
next(search)
i = input("Enter name: ")
search.send(i)
input("Press any key: ")
search.close()
Output:
C:\Python310\python.exe "A:/Python Tutorial/14. Other
Topics/Coroutines_in_python/2_Coroutines_Chalange.py"
Enter name: Hariom
This Name is available in the latter!
Press any key:
Enter name: Abhishek Rajput
This text is not available in the latter!
Press any key:
Enter name: Pooja Mewada
Python tutorial
def product(*args):
prd = 1
for i in args:
prd = prd * i
return prd
a = Module1.add(2, 4, 5, 4)
Python tutorial
print("Sum = ", a)
a = Module1.diff(50, 30)
print("Difference = ", a)
a = Module1.div(49, 3)
print("Division = ", a)
a = Module1.product(20, 4, 5)
print("Product = ", a)
Output:
Sum = 15
Difference = 20
Division = 16.333333333333332
Product = 400
Division = 2.0
def __init__(self):
print("Well come to car show room.")
def wish_morning(string):
print(f"Hello! Good Morning {string}, How are you? ")
print(f"Thanks {string} for looking the car. Have a nice day.")
class Audi(car):
def __init__(self):
self.models = ['q7', 'a6', 'a8', 'a3']
def outModels(self):
print('These are the available models for Audi')
for model in self.models:
print('\t%s ' % model)
class Bmw(car):
def __init__(self):
self.models = ['i8', 'x1', 'x5', 'x6']
def outModels(self):
print('These are the available models for BMW')
for model in self.models:
print('\t%s ' % model)
class Nissan(car):
def __init__(self):
self.models = ['altima', '370z', 'cube', 'rogue']
def outModels(self):
print('These are the available models for Nissan')
for model in self.models:
print('\t%s ' % model)
creating Package_Hariom-1.0.3
creating Package_Hariom-1.0.3\Package_Hariom
creating Package_Hariom-1.0.3\Package_Hariom.egg-info
copying files to Package_Hariom-1.0.3...
copying Licence.txt -> Package_Hariom-1.0.3
copying setup.py -> Package_Hariom-1.0.3
copying Package_Hariom\__init__.py -> Package_Hariom-1.0.3\
Package_Hariom
copying Package_Hariom.egg-info\PKG-INFO ->
Package_Hariom-1.0.3\Package_Hariom.egg-info
Python tutorial
running install
running install_lib
creating build\bdist.win-amd64
creating build\bdist.win-amd64\wheel
creating build\bdist.win-amd64\wheel\Package_Hariom
copying build\lib\Package_Hariom\__init__.py -> build\bdist.win-
amd64\wheel\.\Package_Hariom
running install_egg_info
Copying Package_Hariom.egg-info to build\bdist.win-amd64\
wheel\.\Package_Hariom-1.0.3-py3.10.egg-info
running install_scripts
adding license file "Licence.txt" (matched pattern
"LICEN[CS]E*")
creating build\bdist.win-amd64\wheel\Package_Hariom-
1.0.3.dist-info\WHEEL
creating 'dist\Package_Hariom-1.0.3-py3-none-any.whl' and
adding 'build\bdist.win-amd64\wheel' to it
adding 'Package_Hariom/__init__.py'
adding 'Package_Hariom-1.0.3.dist-info/Licence.txt'
adding 'Package_Hariom-1.0.3.dist-info/METADATA'
Python tutorial
adding 'Package_Hariom-1.0.3.dist-info/WHEEL'
adding 'Package_Hariom-1.0.3.dist-info/top_level.txt'
adding 'Package_Hariom-1.0.3.dist-info/RECORD'
removing build\bdist.win-amd64\wheel
Command 2:
PS A:\Python Tutorial\Creating_python_packege> cd .\dist\
Command 3:
PS A:\Python Tutorial\Creating_python_packege\dist> ls
Output:
Directory: A:\Python Tutorial\Creating_python_packege\dist
Command 4:
PS A:\Python Tutorial\Creating_python_packege\dist> pip
install .\Package_Hariom-1.0.3-py3-none-any.whl
Output:
Processing a:\python tutorial\creating_python_packege\dist\
package_hariom-1.0.3-py3-none-any.whl
Installing collected packages: Package-Hariom
Successfully installed Package-Hariom-1.0.3
>>> a = Package_Hariom.car()
Well come to car show room.
>>> Package_Hariom.wish_morning("Hariom")
Hello! Good Morning Hariom, How are you?
Thanks Hariom for looking the car. Have a nice day.
>>> b = Package_Hariom.Audi()
>>> b.outModels()
These are the available models for Audi
q7
a6
a8
a3
>>> c = Package_Hariom.Nissan()
>>> c.outModels()
These are the available models for Nissan
altima
370z
cube
Python tutorial
rogue
>>>exit()
This is all about that how to create and access python package.
Euler’s Number
The math.e constant returns the Euler’s number:
2.71828182846.
Syntax:
Python tutorial
math.e
Example:
# Import math Library
import math
Output:
2.718281828459045
Pi
You all must be familiar with pi. The pi is depicted as either 22/7
or 3.14. math.pi provides a more precise value for the pi.
Syntax:
math.pi
Example:
# Import math Library
import math
Output:
3.141592653589793
Tau
Tau is defined as the ratio of the circumference to the radius of
Python tutorial
Output:
6.283185307179586
Infinity
Infinity basically means something which is never-ending or
boundless from both directions i.e. negative and positive. It
cannot be depicted by a number. The math.inf constant returns
of positive infinity. For negative infinity, use -math.inf.
Syntax:
math.inf
Example:
# Import math Library
import math
Output:
inf
-inf
NaN
The math.nan constant returns a floating-point nan (Not a
Number) value. This value is not a legal number. The nan
constant is equivalent to float(“nan”).
Example:
# Import math Library
import math
Output:
nan
Numeric Functions
Finding the ceiling and the floor value
Ceil value means the smallest integral value greater than the
number and the floor value means the greatest integral value
smaller than the number. This can be easily calculated using
the ceil() and floor() method respectively.
Python tutorial
Example:
import math
a = 2.3
Output:
The ceil of 2.3 is : 3
The floor of 2.3 is : 2
Finding the factorial of the number
Using the factorial() function we can find the factorial of a
number in a single line of the code. An error message is
displayed if number is not integral or is negative.
Example:
import math
a = 5
Output:
The factorial of 5 is : 120
Python tutorial
a = 15
b = 5
Output:
The gcd of 5 and 15 is : 5
Finding the absolute value
fabs() function returns the absolute value of the number.
Example:
import math
a = -10
Output:
The absolute value of -10 is : 10.0
Python tutorial
Output:
0.0
2.0
1.8708286933869707
Finding the power of a number
pow() function computes x**y. This function first converts its
arguments into float and then computes the power.
Example:
print ("The value of 3^4 is : ", pow(3,4))
Output:
The value of 3^4 is : 81.0
Python tutorial
# exp() method is used to calculate the power of e i.e. e^y or we can say exponential of y.
print(f"e^3 is: {math.exp(4)}, e^-3 is: {math.exp(-3)} and e^0 is: {math.exp(0)}")
Output:
e^3 is: 54.598150033144236, e^-3 is: 0.049787068367863944
Python tutorial
a = math.pi / 6
Output:
The value of sine of pi/6 is : 0.49999999999999994
The value of cosine of pi/6 is : 0.8660254037844387
The value of tangent of pi/6 is : 0.5773502691896257
Converting values from degrees to radians and vice versa
Python tutorial
a = math.pi / 6
b = 30
Output:
The converted value from radians to degrees is :
29.999999999999996
The converted value from degrees to radians is :
0.5235987755982988
hypot(a, b) :
This returns the hypotenuse of the values passed in
arguments. Numerically, it returns the value of sqrt(a*a + b*b).
Example:
import math
a = 3
b = 4
Output:
The value of hypotenuse of 3 and 4 is : 5.0
Special Functions
Finding gamma value
The gamma() function is used to return the gamma value of the
argument.
Check if the value is infinity or NaN
isinf() function is used to check whether the value is infinity or
not.
Output:
Python tutorial
For example - We search the Python tutorial on Google. Then the request sends an
HTTP request to the Google server, and the server returns the searched result with the
status code.
There are two main components to initiate the communication - Client and Server. We
use HTTP (Hypertext Transfer Protocol), which enables the communication between a
client and server over the Internet.
Python provides the requests module, which allows us to make these requests using the
Python script.
It is the most powerful tool of Python that allows us to send requests on the web. It
includes many features and methods to send HTTP requests. The system that sends
requests is known as the client, and the system that holds the webserver is known as a
server.
Python tutorial
While working with the requests, we will come across the following methods.
The Python request module consists of many simple API that is helpful to handle those
requests. These API has many features such as adding headers, sending custom headers,
passing parameters with URLs, and many others.
The GET and POST methods determine the user action on the web pages. The GET is one
of the most general-purpose methods of the Python requests module. It specifies that the
user is attempting to retrieve data from a specified resource. In other words, it is used to
send a request to a URL. To invoke the GET request, we use the following syntax.
In the above method, the URL ARGUMENT is the URL of the particular website where the
user sends the request. The PARAM argument is used to send a query string in the
dictionary and the ARGS is one of the multiple named arguments.
When the get request is successfully sent, the method will return
a requests.Response object. This object saves the response received from the server.
We can assign get() request result in variable.
This object saves the response received from the server. Therefore, we can assign get() request
results in a variable.
Here the response object will store the information. Below are the essential properties.
Example:
import requests
r = requests.get("https://www.hackerrank.com/domains/data-structures?filters%5Bdifficulty%5D%5B
%5D=easy")
print("r = ", r)
print("Status Code is: ", r.status_code)
print("Encoding = ", r.encoding) # returns 'utf-8'
print("Elapsed = ", r.elapsed) # returns datetime.timedelta(0, 1, 666890)
print("Url = ", r.url) # returns given URL
print("History = ", r.history)
print("Content = ", r.content)
print("Cookies = ", r.cookies)
print("Headers = ", r.headers['Content-Type'])
print("Text = ", r.text)
Output:
r = <Response [403]>
Status Code is: 403
Encoding = ISO-8859-1
Elapsed = 0:00:00.427975
Url = https://www.hackerrank.com/domains/data-structures?
filters%5Bdifficulty%5D%5B%5D=easy
History = []
Content = b'<HTML><HEAD>\n<TITLE>Access
Denied</TITLE>\n</HEAD><BODY>\n<H1>Access
Denied</H1>\n \nYou don\'t have permission to access
"http://www.hackerrank.com/do
mains/data-structures?" on this server.<P>\
nReference #18.8efdd417.1645189469
6;c6f203a\n</BODY>\n</HTML>\n'
Python tutorial
Cookies = <RequestsCookieJar[]>
Headers = text/html
Text = <HTML><HEAD>
<TITLE>Access Denied</TITLE>
</HEAD><BODY>
<H1>Access Denied</H1>
form.
o url - The url is a mandatory parameter that indicates URL where we want to send
some data.
o data - It specifies a dictionary, file object, or tuple that we want to send to the URL.
It is an optional parameter.
o json - This is the JSON object to be sent to the URL.
JSON Response
JSON represents the JavaScript Object Notation which is a most popular way to
transmitting the data format. JSON data can be easily readable by the web-browser. The
data is stored in the dictionary form (key, value pair).
STORING IN A VARIABLE
The JSON data can be converted to be Python dictionary and can also store in a variable.
Example:
import requests
json_data = {'username': 'Hariom', 'password': '1234'}
Python tutorial
r = requests.post('https://httpbin.org/post', data=json_data)
# convert JSON to Python Dictionary
print(r.json())
# Storing in a variable
r_dictionary = r.json()
print(r_dictionary['form'])
Output:
{'args': {}, 'data': '', 'files': {}, 'form': {'password': '1234',
'username': 'Hariom'}, 'headers': {'Accept': '*/*', 'Accept-
Encoding': 'gzip, deflate', 'Content-Length': '29', 'Content-Type':
'application/x-www-form-urlencoded', 'Host': 'httpbin.org', 'User-
Agent': 'python-requests/2.27.1', 'X-Amzn-Trace-Id': 'Root=1-
620f9e35-0466c2c678fb953a280fe838'}, 'json': None, 'origin':
'49.35.164.116', 'url': 'https://httpbin.org/post'}
{'password': '1234', 'username': 'Hariom'}
Advantages of using POST Method
It is more secure than GET because user-entered
information is never visible in the URL query string or in the
server logs.
There is a much larger limit on the amount of data that can
be passed and one can send text data as well as binary
data (uploading a file) using POST.
Disadvantages of using the POST Method
Since the data sent by the POST method is not visible in the
URL, so it is not possible to bookmark the page with specific
query.
POST requests are never cached
POST requests do not remain in the browser history.
Python tutorial
o String
o Number
o Boolean
o Null
o Object
o Array
Deserialization of JSON
The Deserialization of JSON means the conversion of JSON
objects into their respective Python objects. The load()/loads()
method is used for it. If you have used JSON data from another
program or obtained as a string format of JSON, then it can
Python tutorial
object dict
array list
string str
null None
true True
false False
json.load():
json.load() accepts file object, parses the JSON data, populates
a Python dictionary with the data and returns it back to you.
Python tutorial
Syntax:
json.load(file object)
Example: Suppose the JSON file looks like this:
{
"Emp_Details": [
{
"Emp_name": "Hariom",
"Email": "[email protected]",
"Job profile": "Developer"
},
{
"Emp_name": "Abhishek",
"Email": "[email protected]",
"Job profile": "Intern"
},
{
"Emp_name": "Karan",
"Email": "[email protected]",
"Job profile": "Full time"
}
]
}
# Closing file
f.close()
Output:
<class 'dict'>
{'Emp_name': 'Hariom', 'Email':
Python tutorial
json.loads():
If you have a JSON string, you can parse it by using the
json.loads() method.json.loads() does not take the file path, but
the file contents as a string, using fileobject.read() with
json.loads() we can return the content of the file.
Syntax:
json.loads(jsonstring) #for Json string
json.loads(fileobject.read()) #for fileobject
# JSON string
a = '{"name": "Hariom", "languages": "Hindi"}'
# JSON file
f = open('data.json', "r")
# Closing file
f.close()
Output:
JSON string = {'name': 'Hariom', 'languages': 'Hindi'}
# Data to be written
dictionary = {
"id": "04",
"name": "Hariom",
"department": "HR",
"Employee": True,
"Extra": None
}
print("Python Object: ", dictionary)
print("Type: ", type(dictionary), "\n")
# Serializing json
json_object = json.dumps(dictionary, indent=4)
print("Json Object: ", json_object)
print("Type: ", type(json_object))
Output:
Python Object: {'id': '04', 'name': 'Hariom', 'department': 'HR',
'Employee': True, 'Extra': None}
Type: <class 'dict'>
Json Object: {
"id": "04",
"name": "Hariom",
"department": "HR",
Python tutorial
"Employee": true,
"Extra": null
}
Type: <class 'str'>
The following types of Python objects can be converted into
JSON strings:
dict
list
tuple
string
int
float
True
False
None
dict object
str string
True true
False false
None null
# Data to be written
dictionary = {
"Name": "Hariom",
"Roll no.": 56,
"cgpa": 8.6,
"Phone number": "9756770500"
}
Output:
{"Name": "Hariom", "Roll no.": 56, "cgpa": 8.6, "Phone number": "9756770500"}
update():
This method updates the dictionary with elements from another
dictionary object or from an iterable key/value pair.
Example 1: Updating a JSON string.
import json
# JSON data:
x = '{ "organization":"SISTech", "city": "Bhopal","country": "India"}'
Output:
{"organization": "SISTech", "city": "Bhopal", "country": "India",
"pin": 110096}
Example 2: Updating a JSON file.
import json
Python tutorial
# function to add to JSON
def write_json(new_data, filename='data.json'):
with open(filename, 'r+') as file:
# First we load existing data into a dict.
file_data = json.load(file)
# Join new_data with file_data inside Emp_Details
file_data["Emp_Details"].append(new_data)
# Sets file's current position at offset.
file.seek(0)
# convert back to json.
json.dump(file_data, file, indent=4)
y = {"Emp_name": "Nikhil",
"Email": "[email protected]",
"Job profile": "Full Time"
}
write_json(y)
1. dump
2. dumps
3. load
4. loads
The first two methods are used for the pickling process, and the next two methods are
used for the unpickling process.
The difference between dump() and dumps() is that dump() creates the file which
contains the serialization results, and the dumps() returns the string.
For differentiation dumps() from the dump(), the developer can remember that in the
dumps() function, ' s' stands for the string.
The same concept can be applied to the load() and loads() function. The load() function is
used for reading the file for the unpickling process, and the loads() function operates on
the string.
Example:
Pickling(dump) python object into a pickle file:
import pickle
Output:
['Audi', 'Ferrari', 'BMW', 'Maruti Suzuki', 'Lamborghini',
'Mahindra', 'Tata']
Pickling(dumps) and de-pickling(loads) without a file:
import pickle
# database
db = {}
db['Omkar'] = Omkar
db['Jagdish'] = Jagdish
# For storing
b = pickle.dumps(db) # type(b) gives <class 'bytes'>
# For loading
myEntry = pickle.loads(b)
print(myEntry)
Output:
{'Omkar': {'key': 'Omkar', 'name': 'Omkar Pathak', 'age': 21, 'pay':
40000}, 'Jagdish': {'key': 'Jagdish', 'name': 'Jagdish Pathak',
'age': 50, 'pay': 50000}}
Advantages of using Pickle Module:
1. Recursive objects (objects containing references to
themselves): Pickle keeps track of the objects it has
Python tutorial
match = re.search(r'portal', s)
Output
Start Index: 34
End Index: 40
The above code gives the starting index and the ending
index of the string portal.
Note: Here r character (r’portal’) stands for raw string.
Example of raw string:
print(r'\n \t \s')
Output:
\n \t \s
MetaCharacters
To understand the RE analogy, MetaCharacters are useful,
important, and will be used in functions of module re. Below is
the list of metacharacters.
MetaChar
acters Description
Python tutorial
\ – Backslash
The backslash (\) makes sure that the character is not treated in
a special way. This can be considered a way of escaping
metacharacters. For example, if you want to search for the dot(.)
in the string then you will find that dot(.) will be treated as a
special character as is one of the metacharacters (as shown in
the above table). So for this case, we will use the backslash(\)
just before the dot(.) so that it will lose its specialty. See the
below example for a better understanding.
Example:
Python3
import re
s = 'geeks.forgeeks'
# without using \
match = re.search(r'.', s)
print(match)
Python tutorial
# using \
match = re.search(r'\.', s)
print(match)
Output
<_sre.SRE_Match object; span=(0, 1), match='g'>
<_sre.SRE_Match object; span=(5, 6), match='.'>
[] – Square Brackets
Square Brackets ([]) represents a character class consisting of a
set of characters that we wish to match. For example, the
character class [abc] will match any single a, b, or c.
We cal also specify a range of characters using – inside the
square brackets. For example,
[0, 3] is sample as [0123]
[a-c] is same as [abc]
We can also invert the character class using the caret(^)
symbol. For example,
[^0-3] means any number except 0, 1, 2, or 3
[^a-c] means any character except a, b, or c
^ – Caret
Caret (^) symbol matches the beginning of the string i.e. checks
whether the string starts with the given character(s) or not. For
Python tutorial
example –
^g will check if the string starts with g such as geeks, globe,
girl, g, etc.
^ge will check if the string starts with ge such as geeks,
geeksforgeeks, etc.
$ – Dollar
Dollar($) symbol matches the end of the string i.e checks
whether the string ends with the given character(s) or not. For
example –
s$ will check for the string that ends with a such as geeks,
ends, s, etc.
ks$ will check for the string that ends with ks such as geeks,
geeksforgeeks, ks, etc.
. – Dot
Dot(.) symbol matches only a single character except for the
newline character (\n). For example –
a.b will check for the string that contains any character at
the place of the dot such as acb, acbd, abbb, etc
.. will check if the string contains at least 2 characters
| – Or
Or symbol works as the or operator meaning it checks whether
the pattern before or after the or symbol is present in the string
or not. For example –
Python tutorial
Special
Seque
nce Description Examples
for
geeks
\ for
Matches if the string begins Afo the
\A with the given character r world
Python tutorial
Special
Seque
nce Description Examples
toget
It is the opposite of the \b i.e. \ her
the string should not start or Bg
\B end with the given regex. e forge
gee
ks
Matches any whitespace
\s character. \s a bc a
Python tutorial
Special
Seque
nce Description Examples
a bd
Matches any non-whitespace
\S character \S abcd
123
Matches any alphanumeric
character, this is equivalent to geeK
\w the class [a-zA-Z0-9_]. \w s4
>$
abcda
b
# Row String
print(r"\n")
Mystr = '''Python has wide range of libraries and frameworks widely used in various fields such as
machine learning,
artificial intelligence, web applications, etc. We define some popular frameworks and libraries of
Python
as follows.
Python tutorial
1. Web development (Server-side) - Django Flask, Pyramid, CherryPy
2. GUIs based applications - Tk, PyGTK, PyQt, PyJs, etc.
3. Machine Learning - TensorFlow, PyTorch, Scikit-learn, Matplotlib, Scipy, etc.
4. Mathematics - Numpy, Pandas, etc.
now number is: 12398-873
now number is: 20098-233
contact numbers :
+919876012765
+919876876765
+919765012765
+919876019886
+918897612765
+919980007665
'''
# m = re.compile(r'applications')
# m = re.compile(r'.') # Iterate any charecter
# m = re.compile(r'^Python') # Start with python
# m = re.compile(r'tc.$') # Ends with tc
# m = re.compile(r'm*a*') # Zero or more occurrence
# m = re.compile(r'ma+') # One or more occurrence
# m = re.compile(r'ap{2}') # Exact number
# m = re.compile(r'ap{1}|py') # Either or
# special sequences
# m = re.compile(r'\APython') # start with python
# m = re.compile(r'\bapp') # start with app
# m = re.compile(r'ment\b') # end with ment
# m = re.compile(r'\d{5}-\d{3}')
m = re.compile(r'\b91\d{10}')
matches = m.finditer(Mystr)
for match in matches:
print(match)
Functions of re module:
re.findall()
Return all non-overlapping matches of pattern in string, as a list
of strings. The string is scanned left-to-right, and matches are
returned in the order found.
Example: Finding all occurrences of a pattern
import re
regex = '\d+'
Python tutorial
match = re.findall(regex, string)
print(match)
Output:
['1234567898', '9869234560', '9876543921', '9870543670']
re.compile()
Regular expressions are compiled into pattern objects, which
have methods for various operations such as searching for
pattern matches or performing string substitutions.
Example:
import re
p = re.compile('[a-e]')
print(p.findall("Aye, said Mr. Gibenson Stark"))
print()
# \d is equivalent to [0-9].
p = re.compile('\d')
print(p.findall("I went to him at 11 A.M. on 4th July 1886"))
# \w is equivalent to [a-zA-Z0-9_].
p = re.compile('\w')
print(p.findall("He said * in some_lang."))
Output:
['e', 'a', 'd', 'b', 'e', 'a']
Python tutorial
['H', 'e', 's', 'a', 'i', 'd', 'i', 'n', 's', 'o', 'm', 'e', '_', 'l', 'a', 'n', 'g']
['I', 'went', 'to', 'him', 'at', '11', 'A', 'M', 'he', 'said', 'in',
'some_language']
[' ', ' ', '*', '*', '*', ' ', ' ', '.']
re.split()
Split string by the occurrences of a character or a pattern, upon
finding that pattern, the remaining characters from the string are
returned as part of the resulting list.
Example:
from re import split
Output:
['Words', 'words', 'Words']
['Word', 's', 'words', 'Words']
['On', '12th', 'Jan', '2016', 'at', '11', '02', 'AM']
['On ', 'th Jan ', ', at ', ':', ' AM']
re.sub()
The ‘sub’ in the function stands for SubString, a certain regular
expression pattern is searched in the given string(3rd
parameter), and upon finding the substring pattern is replaced
by repl(2nd parameter), count checks and maintains the number
of times this occurs.
Example:
import re
Output:
S~*ject has ~*er booked already
S~*ject has Uber booked already
re.subn()
Python tutorial
Output:
('S~*ject has Uber booked already', 1)
('S~*ject has ~*er booked already', 2)
2
S~*ject has ~*er booked already
re.escape()
Returns string with all non-alphanumerics backslashed, this is
useful if you want to match an arbitrary literal string that may
have regular expression metacharacters in it.
Example:
import re
Output:
This\ is\ Awesome\ even\ 1\ AM
I\ Asked\ what\ is\ this\ \[a\-9\]\,\ he\ said\ \ \ \^WoW
re.search()
This method either returns None (if the pattern doesn’t match),
or a re.MatchObject contains information about the matching
part of the string. This method stops after the first match, so this
is best suited for testing a regular expression more than
extracting data.
Example:
import re
s = "Welcome to Anandipura!"
res = re.search(r"\bA", s)
print(res)
print(res.re)
print(res.string)
print()
print(search.start())
print(search.end())
print(search.span())
Output:
Python tutorial
11
15
(11, 15)
print(sys.version)
Output:
3.10.2 (tags/v3.10.2:a58ebcc, Jan 17 2022, 14:12:15) [MSC
Python tutorial
stdin
stdout
stderr
stdin: It can be used to get input from the command line
directly. It used is for standard input. It internally calls the input()
method. It, also, automatically adds ‘\n’ after each sentence.
Example:
import sys
print("Exit")
Output:
hariom mewada
Input : hariom mewada
Python tutorial
hello friends
Input : hello friends
okay byy
Input : okay byy
q
Exit
Stdout: stdout is used to display output directly to the screen
console.
Example:
import sys
sys.stdout.write("I am Hariom")
Output:
I am Hariom
print_to_stderr("Hello World")
Output:
Hello World
Exiting the Program
sys.exit([arg]) can be used to exit the program.
Note: A string can also be passed to the sys.exit() method.
Example:
import sys
while True:
age = int(input("Enter age: "))
if age < 18:
# exits the program
sys.exit("Age less than 18")
else:
print("Age is not less than 18")
Output:
Enter age: 32
Age is not less than 18
Enter age: 21
Age is not less than 18
Enter age: 18
Age is not less than 18
Python tutorial
Enter age: 17
Age less than 18
Argparse Module
The argparse module in Python helps create a program in a
command-line-environment in a way that appears not only easy
to code but also improves interaction. The argparse module also
automatically generates help and usage messages and issues
errors when users give the program invalid arguments.
Example: Command line utility
import argparse
import sys
def calc(args):
if args.o == 'add':
return args.x + args.y
else:
return "Something went wrong"
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('--x', type=float, default=0.0,
help="Enter first number. This is a utility for calculation. For more
information please contact on 1001 2002 3003")
Output:
PS A:\Python Tutorial\14. Other Topics> python .\
Command_line_utility.py --x 10 --y 20 --o add
30.0
PS A:\Python Tutorial\14. Other Topics> python .\
Command_line_utility.py --x 54 --y 34 --o sub
20.0
PS A:\Python Tutorial\14. Other Topics> python .\
Command_line_utility.py --x 20 --y 10 --o mul
200.0
PS A:\Python Tutorial\14. Other Topics> python .\
Command_line_utility.py --x 20 --y 10 --o div
2.0
PS A:\Python Tutorial\14. Other Topics> python .\
Command_line_utility.py --x 20 --y 10 --o rem
Something went wrong
Step 2:
Go into the directory where your ‘.py’ file is located.
Step 3:
Press the shift⇧ button and simultaneously right-click at the
same location and Click on ‘Open PowerShell window here’.
Step 4:
Type the command given below in that PowerShell window.
pyinstaller 'filename.py'
Note: This will convert python file into exe file but at the same
time it will create many other files and .exe file will depends on
them.
So, if we want to create single and independent exe file, then
type this command:
pyinstaller --onefile 'filename.py'
Note: This will convert python file into one exe file which is
Python tutorial
Installation in Windows:
Create an application
Python tutorial
class MinAPP(MDApp):
def build(self):
return MDLabel(text="My first android app", halign="center")
if __name__ == '__main__':
MinAPP().run()
Output:
Python tutorial
Note: for converting python file into apk file, the file name
should be main.py
Now there is the following steps written below to convert
this python file into apk file:
1. Now, search google colab on chrome
2. Click on New Notebook
Now type some code on google colab code editor:
Python tutorial
First :
!pip install buildozer
Second :
!pip install cython==0.29.19
Third :
!sudo apt-get install -y \
python3-pip \
build-essential \
git \
python3 \
python3-dev \
ffmpeg \
libsdl2-dev \
libsdl2-image-dev \
libsdl2-mixer-dev \
libsdl2-ttf-dev \
libportmidi-dev \
libswscale-dev \
libavformat-dev \
libavcodec-dev \
zlib1g-dev
Forth :
!sudo apt-get install -y \
libgstreamer1.0 \
gstreamer1.0-plugins-base \
gstreamer1.0-plugins-good
Fifth :
!sudo apt-get install build-essential libsqlite3-dev sqlite3 bzip2 libbz2-dev zlib1g-
dev libssl-dev openssl libgdbm-dev libgdbm-compat-dev liblzma-dev libreadline-dev libn
cursesw5-dev libffi-dev uuid-dev libffi6
Sixth :
Python tutorial
!sudo apt-get install libffi-dev
Now your apk will be created. This process may take some time.
Python tutorial
Python - Data structures
Data Structure Overview
Data structures are fundamental concepts of computer science which helps is writing efficient
programs in any language. Python is a high-level, interpreted, interactive and object-oriented
scripting language using which we can study the fundamentals of data structure in a simpler way as
compared to other programming languages.
Stack operations:
1. Push Inserting an element.
2. Pop Deleting last element from
stack.
3. Peek Display the last element.
4. Display Display list.
Python tutorial
Example:
# Creating Stack using list
list1 = []
while True:
choice = int(input('''
_______________Choose any option for continue_________________
1. Push Element
2. Pop Element
3. Peek Element
4. Display Stack
5. Exit
'''))
if choice == 1:
new_Element = int(input("\nEnter new element: "))
list1.append(new_Element)
print("Your Stack is: ", list1)
elif choice == 2:
if len(list1) == 0:
print("Stack is Empty!")
else:
popped_element = list1.pop()
print("Popped element is: ", popped_element)
print("Now your Stack is: ", list1)
Python tutorial
elif choice == 3:
if len(list1) == 0:
print("Stack is Empty!")
else:
print("Last element of stack is: ", list1[-1])
elif choice == 4:
print("Displaying Stack : ", list1)
elif choice == 5:
break
else:
print("Invalid Input! ")
Queue:
The Queue is a linear data structure.
Stores items in First In First Out (FIFO) manner.
Queue operations:
1. Enqueue Add an item to the
Queue.
2. Dequeue Remove an item from
the Queue.
3. Front Get the front item from
queue.
4. Rear Get the last item from queue.
Python tutorial
Example:
# Creating Queue using list
list1 = []
while True:
choice = int(input('''
_______________Choose any option for continue_________________
1. Enqueue Element
2. Dequeue Element
3. Get Front Element
4. Get Rear Element
5. Display Queue
6. Exit
'''))
if choice == 1:
new_Element = int(input("\nEnter new element: "))
list1.append(new_Element)
print("Your Queue is: ", list1)
elif choice == 2:
if len(list1) == 0:
print("Queue is Empty!")
else:
print("Dequeueing element is: ", list1[0])
del list1[0]
print("Now your Queue is: ", list1)
Python tutorial
elif choice == 3:
if len(list1) == 0:
print("Queue is Empty!")
else:
print("Front element of Queue is: ", list1[0])
elif choice == 4:
if len(list1) == 0:
print("Queue is Empty!")
else:
print("Last element of Queue is: ", list1[-1])
elif choice == 5:
print("Displaying Queue: ", list1)
elif choice == 6:
break
else:
print("Invalid Input!")