0% found this document useful (0 votes)
5 views343 pages

Python Tutorial Notes

This document is a comprehensive tutorial on Python, covering its introduction, history, features, and applications. It explains the differences between Python 2 and Python 3, provides examples of basic programming concepts, and lists various operators available in Python. Additionally, it discusses popular frameworks, libraries, and the use of pip for package management.

Uploaded by

thehsr484
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views343 pages

Python Tutorial Notes

This document is a comprehensive tutorial on Python, covering its introduction, history, features, and applications. It explains the differences between Python 2 and Python 3, provides examples of basic programming concepts, and lists various operators available in Python. Additionally, it discusses popular frameworks, libraries, and the use of pip for package management.

Uploaded by

thehsr484
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 343

Python tutorial

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 is easy to learn yet powerful and versatile scripting


language, which makes it attractive
for Application Development.
Python makes the development and debugging fast because there
is no compilation step included in Python
development, and edit-test-debug cycle is very fast.

Python 2 vs. Python 3


A list of differences between Python 2 and Python 3 are given below:
1. Python 2 uses print as a statement and used as print
"something" to print some string on
the console. On the other hand, Python 3 uses print as a
function and used as
print("something") to print something on the console.

2. Python 2 uses the function raw_input() to accept the user's


input. It returns the string to
representing the value, which is typed by the user. To convert
it into the integer, we need
Python tutorial
use the int() function in Python. On the other hand, Python 3
uses input() function which
automatically interpreted the type of input entered by the
user. However, we can cast this
value to any type by using primitive functions (int(), str(),
etc.)

3. In Python 2, the implicit string type is ASCII, whereas, in


Python 3, the implicit string type
is Unicode.

4. Python 3 doesn't contain the xrange() function of Python 2.


The xrange() is the variant of
range() function which returns a xrange object that works
similar to Java iterator. The
range() returns a list for example the function range(0,3)
contains 0, 1, 2.

5. There is also a small change made in Exception handling in


Python 3. It defines a section
keyword as which is necessary to be used. We will discuss it
in Exception handling
of Python programming tutorial.

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.

Why learn Python?


Python provides many useful features to the programmer. These
features make it most popular and widely
used language. We have listed below few-essential feature of
Python.
o Easy to use and Learn

o Expressive Language

o Interpreted Language

o Object-Oriented Language

o Open Source Language

o Extensible

o Learn Standard Library

o GUI Programming Support

o Integrated

o Embeddable

o Dynamic Memory Allocation

o Wide Range of Libraries and Frameworks

Where is Python used?


Python tutorial
Python is a general-purpose, popular programming language and it
is used in almost every technical field.
The various areas of Python use are given below.
o Data Science

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 Computer Vision or Image Processing Applications.

o Speech Recognitions

Python Popular Frameworks and Libraries


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
o Web development (Server-side) - Django Flask, Pyramid,
CherryPy

o GUIs based applications - Tk, PyGTK, PyQt, PyJs, etc.

o Machine Learning - TensorFlow, PyTorch, Scikit-learn,


Matplotlib, Scipy, etc.

o Mathematics - Numpy, Pandas, etc.

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 pip install packages


We can install additional packages by using the Python pip
install command. Let’s suppose we want to
install the numpy using pip. We can do it using the below
command.
Syntax:
<pip install numpy

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

First Python Program:


print("Hello world")
Output:
Hello world

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.

print() function: This is used to print a string.


Example:
print("Hello friends\nGood morning") # \n is used for a new line
print("My name is","harion Singh Rajput") #This will print both
strings in a single line with a space
print("Hey! What's up Guys") # By default python gets a new line
between two print statements
Output:
Hello friends
Good morning
My name is harion Singh Rajput
Hey! What's up Guys

Preventing Escape Sequence Interpretation in Python


Escape Sequence is a combination of characters (usually prefixed
with an escape character), that has a
non-literal character interpretation. Such that, the characters
sequences which are considered as an
Python tutorial
escape sequence have a meaning other than the literal characters
contained therein.

List of Escape Sequence in Python:


Escape Character Meaning
\’ Single quote
\” Double quote
\\ backslash
\n New line
\r Carriage Return
\t Horizontal tab
\b Backspace
\f form feed
\v vertical tab
\0 Null character
\N{name} Unicode Character Database named Lookup
\uxxxxxxxx Unicode Character with 16-bit hex value XXXX
\Uxxxxxxxx Unicode Character with 32-bit hex value XXXXXXXX
\ooo Character with octal value OOO
\xhh Character with hex value HH
Example:
# A string with a recognized escape sequence
print("I will go\tHome")

# A string with a unrecognized escape sequence


print("See you\jtommorow")

# doubling line backslashes


s = "I love to use \\t instead of using 4 spaces"
print(s)
Output:
I will go Home
See you\jtommorow
I love to use \t instead of using 4 spaces
Python tutorial

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

asset def class continue break

else finally elif del except

global for if from import

raise try or return pass

nonlocal in not is lambda

Typecasting by using eval in python:


eval is used to typecast the data in any data type like int , float,
etc. but not in string.
Example:
# eval is used to typecast the data in any data type like int , float,
etc. but not in string
a1 = eval(input("Enter a1 : "))
b1 = eval(input("Enter b1 : "))

print("Addition/Concatenation: ", a1+b1)

a2 = eval(input("Enter a2 : "))
b2 = eval(input("Enter b2 : "))

print("Addition/Concatenation: ", a2+b2)


Python tutorial

a3 = eval(input("Enter a3 : "))
b3 = eval(input("Enter b3 : "))

print("Addition/Concatenation: ", a3+b3)


Output:
Enter a1 : 10
Enter b1 : 20
Addition/Concatenation: 30
Enter a2 : 20
Enter b2 : 45.7
Addition/Concatenation: 65.7
Enter a3 : 0b1010
Enter b3 : 20
Addition/Concatenation: 30

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

Arithmetic operators are used to perform arithmetic operations


between two operands. It includes + (addition), - (subtraction),
*(multiplication), /(divide), %(reminder), //(floor division), and
exponent (**) operators.

Consider the following table for a detailed explanation of


arithmetic operators.

Operator Description

+ It is used to add two operands. For example, if a


(Addition = 20, b = 10 => a+b = 30
)
- It is used to subtract the second operand from
(Subtracti the first operand. If the first operand is less than
on) the second operand, the value results negative.
For example, if a = 20, b = 10 => a - b = 10
/ (divide) It returns the quotient after dividing the first
operand by the second operand. For example, if a
= 20, b = 10 => a/b = 2.0
* It is used to multiply one operand with the other.
(Multiplic For example, if a = 20, b = 10 => a * b = 200
ation)
% It returns the reminder after dividing the first
(reminder operand by the second operand. For example, if a
) = 20, b = 10 => a%b = 0
** It is an exponent operator represented as it
(Exponen calculates the first operand power to the second
t) operand.
// (Floor It gives the floor value of the quotient produced
Python tutorial

division) by dividing the two operands.


Example:
a = 25
b=2
print("25 + 2 = ", a+b)
print("25 - 2 = ", a-b)
print("25 * 2 = ", a*b)
print("25 / 2 = ", a/b)
print("25 % 2 = ", a%b) # It gives remainder
print("25 // 2 = ", a//b) # It gives division in integer and ignore
values after point
print("25 ** 2 = ", a**b) # It returns a to the power b
Output:
25 + 2 = 27
25 - 2 = 23
25 * 2 = 50
25 / 2 = 12.5
25 % 2 = 1
25 // 2 = 12
25 ** 2 = 625

Comparison operator

Comparison operators are used to comparing the value of the two


operands and returns Boolean true or false accordingly. The
comparison operators are described in the following table.

Oper Description
ator

== If the value of two operands is equal, then the


condition becomes true.
!= If the value of two operands is not equal, then the
Python tutorial

condition becomes true.


<= If the first operand is less than or equal to the second
operand, then the condition becomes true.
>= If the first operand is greater than or equal to the
second operand, then the condition becomes true.
> If the first operand is greater than the second
operand, then the condition becomes true.
< If the first operand is less than the second operand,
then the condition becomes true.
Example:
a = 10
b=5
print(a == b)
print(a < b)
print(a > b)
print(a <= b)
print(a >= b)
print(a != b)
Output:
False
False
True
False
True
True

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

described in the following table.

Oper Description
ator

= It assigns the value of the right expression to the left


operand.
+= It increases the value of the left operand by the value
of the right operand and assigns the modified value
back to left operand. For example, if a = 10, b = 20
=> a+ = b will be equal to a = a+ b and therefore, a
= 30.
-= It decreases the value of the left operand by the
value of the right operand and assigns the modified
value back to left operand. For example, if a = 20, b
= 10 => a- = b will be equal to a = a- b and
therefore, a = 10.
*= It multiplies the value of the left operand by the value
of the right operand and assigns the modified value
back to then the left operand. For example, if a = 10,
b = 20 => a* = b will be equal to a = a* b and
therefore, a = 200.
%= It divides the value of the left operand by the value of
the right operand and assigns the reminder back to
the left operand. For example, if a = 20, b = 10 => a
% = b will be equal to a = a % b and therefore, a = 0.
**= a**=b will be equal to a=a**b, for example, if a = 4,
b =2, a**=b will assign 4**2 = 16 to a.
//= A//=b will be equal to a = a// b, for example, if a = 4,
b = 3, a//=b will assign 4//3 = 1 to a.
Python tutorial
Example:
a = 25
b=5
print("a = ", a)
print("b = ", b)
a += b # a = a+b
print("a + b = ", a)
a -= b # a = a-b
print("a - b = ", a)
a *= b # a = a*b
print("a * b = ", a)
a /= b # a = a/b
print("a / b = ", a)
a //= 3 # a = a//3
print("a // 3 = ", a)
a **= 2 # a = a ** 2
print("a ^ 2 = ", a)
a %= 7 # a = a%7
print("a % 7 = ", a)
Output:
a = 25
b= 5
a + b = 30
a - b = 25
a * b = 125
a / b = 25.0
a // 3 = 8.0
a ^ 2 = 64.0
a % 7 = 1.0
Python tutorial

Bitwise Operators

The bitwise operators perform bit by bit operation on the values of


the two operands. Consider the following example.

For example,

if a = 7
b = 6
then, binary (a) = 0111
binary (b) = 0110

hence, a & b = 0011


a | b = 0111
a ^ b = 0100
~ a = 1000

Operat Description
or

& If both the bits at the same place in two operands


(binary are 1, then 1 is copied to the result. Otherwise, 0 is
and) copied.
| The resulting bit will be 0 if both the bits are zero;
(binary otherwise, the resulting bit will be 1.
or)
^ The resulting bit will be 1 if both the bits are
(binary different; otherwise, the resulting bit will be 0.
xor)
~ It calculates the negation of each bit of the
(negati operand, i.e., if the bit is 0, the resulting bit will be 1
on) and vice versa.
Python tutorial

<< The left operand value is moved left by the number


(left of bits present in the right operand.
shift)
>> The left operand is moved right by the number of
(right bits present in the right operand.
shift)
Example:
"""
Decimal Binary
0 000
1 001
2 010
3 011
4 100
5 101
"""

# 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

The logical operators are used primarily in the expression


evaluation to make a decision. Python supports the following
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

Python membership operators are used to check the membership


of value inside a Python data structure. If the value is present in
the data structure, then the resulting value is true otherwise it
returns false.

Oper Description
ator

in It is evaluated to be true if the first operand is found


in the second operand (list, tuple, or dictionary).
not in It is evaluated to be true if the first operand is not
found in the second operand (list, tuple, or
dictionary).
Example:
list1 = [5, 6, 9, 11, 54, 23, 98, 55, 100, 17, 9, 14]
print(list1)
print("9 in list1: ", 9 in list1)
print("55 in list1: ", 55 in list1)
print("87 in list1: ", 87 in list1)
print("15 in list1: ", 15 in list1)
Output:
[5, 6, 9, 11, 54, 23, 98, 55, 100, 17, 9, 14]
9 in list1: True
55 in list1: True
87 in list1: False
15 in list1: False

Identity Operators
Python tutorial

The identity operators are used to decide whether an element


certain class or type.

Oper Description
ator

is It is evaluated to be true if the reference present at


both sides point to the same object.
is not It is evaluated to be true if the reference present at
both sides do not point to the same object.
Example:
a = 10
b = 11
print("a = ", a)
print("b = ", b)
print("a is b = ", a is b)
print("a is not b = ", a is not b)

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

** The exponent operator is given priority over all


the others used in the expression.
~+- The negation, unary plus, and minus.
* / % // The multiplication, divide, modules, reminder,
and floor division.
+- Binary plus, and minus
>> << Left shift. and right shift
& Binary and.
^| Binary xor, and or
<= < > Comparison operators (less than, less than equal
>= to, greater than, greater then equal to).
<> == != Equality operators.
= %= Assignment operators
/= //= -=
+=
*= **=
Is, is not Identity operators
In, not in Membership operators
Not, or, Logical operators
and

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)

Here 24, 24.3, 2+3j are considered as literals.

Python Literals can be defined as data that is given in a variable or


constant.

Python supports the following literals:

1. String literals:

String literals can be formed by enclosing a text in the quotes. We


can use both single as well as double quotes to create a string.
Example:

"Aman" , '12345'

Types of Strings:
Python tutorial

There are two types of Strings supported in Python:

a) Single-line String- Strings that are terminated within a single-


line are known as Single line Strings.
Example:

# Single-line String
text1 = 'hello' # By using single quotes
text2 = "Hariom mewada" # By using double quotes
print(text1)
print(text2)
Output:

hello

Hariom mewada

b) Multi-line String - A piece of text that is written in multiple


lines is known as multiple lines string. By using triple quotes we
can write multi-line strings or display in the desired way.
Example:

# Multi-line String
str1 = """hariom
singh
rajput"""

str2 = '''My name is


Hariom Mewada'''
print(str1)
print(str2)
Output:

hariom
Python tutorial

singh

rajput

My name is

Hariom Mewada

II. Numeric literals:

Numeric Literals are immutable. Numeric literals can belong to


following four different numerical types.

Int(signe Long(long float(floati Complex(comple


d integers) ng point) x)
integers)

Numbers( c Integers of Real In the form of a+bj


an be both unlimited numbers where a forms the
positive and size with both real part and b
negative) followed by integer and forms the imaginary
with no lowercase fractional part of the complex
fractional or part eg: - number. eg: 3.14j
part.eg: uppercase L 26.2
100 eg:
87032845L
Example - Numeric Literals

x = 0b101 # Binary Literals


y = 100 # Decimal Literal
z = 0o215 # Octal Literal
u = 0x12d # Hexadecimal Literal

# 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:

20 100 141 301


100.5 150.0
(5+3.14j) 3.14 5.0

III. Boolean literals:

A Boolean literal can have any of the two values: True or False.

Example - Boolean Literals

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

IV. Special literals.

Python contains one special literal i.e., None.

None is used to specify to that field that is not created. It is also


used for the end of lists in Python.

Example - Special Literals

val1=10
val2=None
print(val1)
print(val2)
Output:

10
None

V. Literal Collections.

Python provides the four types of literal collection such as List


literals, Tuple literals, Dict literals, and Set literals.

List:

o List contains items of different data types. Lists are mutable


i.e., modifiable.
o The values stored in List are separated by comma(,) and
enclosed within square brackets([]). We can store different
types of data in a List.

Example - List literals

list=['John',678,20.4,'Peter']
list1=[456,'Andrew']
print(list)
Python tutorial
print(list + list1)
Output:

['John', 678, 20.4, 'Peter']


['John', 678, 20.4, 'Peter', 456, 'Andrew']

Dictionary:

o Python dictionary stores the data in the key-value pair.


o It is enclosed by curly-braces {} and each pair is separated by
the commas(,).
Example

dict = {'name': 'Pater', 'Age':18,'Roll_nu':101}


print(dict)
Output:

{'name': 'Pater', 'Age': 18, 'Roll_nu': 101}

Tuple:

o Python tuple is a collection of different data-type. It is


immutable which means it cannot be modified after creation.
o It is enclosed by the parentheses () and each element is
separated by the comma(,).
Example

tup = (10,20,"Dev",[2,3,4])
print(tup)
Output:

(10, 20, 'Dev', [2, 3, 4])

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(,).

Example: - Set Literals

set = {'apple','grapes','guava','papaya'}
print(set)
Output:

{'guava', 'apple', 'papaya', 'grapes'}

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.

In Python, we don't need to specify the type of variable because


Python is a infer language and smart enough to get variable type.

Identifier Naming

Variables are the example of identifiers. An Identifier is used to


identify the literals used in the program. The rules to name an
identifier are given below.

o The first character of the variable must be an alphabet or


underscore ( _ ).
o All the characters except the first character may be an
alphabet of lower-case(a-z), upper-case (A-Z), underscore, or
digit (0-9).
o Identifier name must not contain any white-space, or special
character (!, @, #, %, ^, &, *).
o Identifier name must not be similar to any keyword defined in
the language.
Python tutorial
o Identifier names are case sensitive; for example, my name,
and MyName is not the same.
o Examples of valid identifiers: a123, _n, n_9, etc.
o Examples of invalid identifiers: 1a, n%4, n 9, etc.
Example:

var1 = "Hariom Singh Rajput!"


var2 = 45
var3 = 49.5
var4 = " Student of SISTech"

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

Hariom Singh Rajput! Student of SISTech

5545

100

Hello, My Name is Hariom Singh Rajput


Python tutorial

Hello, My Name is Hariom Singh Rajput

Hello, My Name is Hariom Singh Rajput

Hello, My Name is Hariom Singh Rajput

Hello, My Name is Hariom Singh Rajput

Hello, My Name is Hariom Singh Rajput

Hello, My Name is Hariom Singh Rajput

Hello, My Name is Hariom Singh Rajput

Hello, My Name is Hariom Singh Rajput

Hello, My Name is Hariom Singh Rajput

Object References

It is necessary to understand how the Python interpreter works


when we declare a variable. The process of treating variables is
somewhat different from many other programming languages.

Python is the highly object-oriented programming language; that's


why every data item belongs to a specific type of class. Consider
the following example.
Example:
var1 = "Hariom Singh Rajput!"
var2 = 45
var3 = 49.5

print(type(var1))
print(type(var2))
print(type(var3))
Output:
Python tutorial

<class 'str'>

<class 'int'>

<class 'float'>

Assigning multiple values to multiple variables:


Example:
a, b, c = 5, 10, 15
print("a = ", a)
print("b = ", b)
print("c = ", c)
Output:

a= 5

b = 10

c = 15

Python Variable Types

There are two types of variables in Python - Local variable and


Global variable. Let's understand the following variables.

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:

The sum is: 50

Global Variables

Global variables can be used throughout the program, and its


scope is in the entire program. We can use global variables inside
or outside the function.

A variable declared outside the function is the global variable by


default. Python provides the global keyword to use global variable
inside the function. If we don't use the global keyword, the
function treats it as a local variable and by using global keyword
we can change the value of global variable inside the function.
Example1:
# Declare a variable and initialize it
x = 101

# Global variable in function


def mainFunction():
# printing a global variable
global x
print(x)
# modifying a global variable
x = 'Welcome My dear Friends'
print(x)
Python tutorial

mainFunction()
print(x)
Output:

101

Welcome My dear Friends

Welcome My dear Friends


Example2:
l = "Hello" # Global variable
def function1(x):
m = 125 # Local variable
print(l, x, "! How are you?")
print(m)

print(l, "HSR")
# print(m) # This will throw an error because m is a local
variable

function1("Hariom")
Output:

Hello HSR

Hello Hariom ! How are you?

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:

Before calling func2 x = 20

After calling func2 x = 20

value of global variable is: 50

Delete a variable

We can delete the variable using the del keyword. The syntax is
given below.

Syntax -

del <variable_name>

In the following example, we create a variable x and assign value


to it. We deleted variable x, and print it, we get the
error "variable x is not defined". The variable x will no longer
use in future.
Example:
# Assigning a value to x
x=6
print(x)
# deleting a variable.
del x
print(x)
Output:
Python tutorial

Traceback (most recent call last):


File "A:\notes Python Tutorial\2. Data types and Variables\
6_Delete_a_Variable.py", line 6, in <module>
print(x)

NameError: name 'x' is not defined

Maximum Possible Value of an Integer in Python

Unlike the other programming languages, Python doesn't have


long int or float data types. It treats all integer values as
an int data type. Here, the question arises. What is the maximum
possible value can hold by the variable in Python? Consider the
following example.
Example -
# A Python program to display that we can store
# large numbers in Python

a = 10000000000000000000000000000000000000000000
a=a+1
print(type(a))
print (a)
Output:
<class 'int'>
10000000000000000000000000000000000000000001

As we can see in the above example, we assigned a large integer


value to variable x and checked its type. It printed class
<int> not long int. Hence, there is no limitation number by bits
and we can expand to the limit of our memory.

Python doesn't have any special data type to store larger numbers.
Python tutorial

Input from Users:


We use input function to take input by user in
python.
Example:
print("Enter first Number")
num1 = input()
print("Enter second number")
num2 = input()
#Because By default data type of any variable is to string that's
why we have to need to typecast them
print("Addition = ", int(num1)+int(num2))
print("Subtraction = ", int(num1)-int(num2))
print("Multiplication = ", int(num1)*int(num2))
print("Division = ", float(num1)/float(num2))

Output:

Enter first Number

95

Enter second number

Addition = 100

Subtraction = 90

Multiplication = 475

Division = 19.0

Value equality vs Reference equality in python:


Example:
a = [2, 4, 6, 8, 10]
Python tutorial
b=a # Value equality
c = a[:] # Reference equality by slicing

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

Python Data Types


Python tutorial

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.

Python creates Number objects when a number is assigned to a


variable. For example;

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:

The type of a <class 'int'>


The type of b <class 'float'>
The type of c <class 'complex'>
c is complex number: True

Python supports three types of numeric data.

1. Int - Integer value can be any length such as integers 10, 2,


29, -20, -150 etc. Python has no restriction on the length of an
integer. Its value belongs to int
2. Float - Float is used to store floating-point numbers like 1.9,
9.902, 15.2, etc. It is accurate upto 15 decimal points.
3. complex - A complex number contains an ordered pair, i.e., x
+ iy where x and y denote the real and imaginary parts,
respectively. The complex numbers like 2.14j, 2.0 + 2.3j, etc.

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.

# Python program to check the boolean type


print(type(True))
print(type(False))
Python tutorial
print(false)

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.

String handling in Python is a straightforward task since Python


provides built-in functions and operators to perform operations in
the string.

In the case of string handling, the operator + is used to


concatenate two strings as the operation "hello"+"
python" returns "hello python".

The operator * is known as a repetition operator as the operation


"Python" *2 returns 'Python Python'.

Syntax:

str = "Hi Python !"

Strings indexing and splitting


Like other languages, the indexing of the Python strings starts
from 0. For example, The string "HELLO" is indexed as given in the
Python tutorial

below figure.

Consider the following example:

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

mystr = "Hariom is a good boy"


print(mystr)
print("Lenght of mystr is: ", len(mystr))
print(mystr[0])
print(mystr[1])
print(mystr[2])
print(mystr[3])
print(mystr[4])
print(mystr[5])
print(mystr[-1]) #Print last character
print(mystr[12:21]) #Printing 12 to 20 characters
print(mystr[0:21:2]) #Print 1 char and skip second char from 0 to
20 characters
print(mystr[0:]) #Print 0 t0 full string
print(mystr[:6]) #Print 0 to 6 characters of string
print(mystr[::]) #Print full string mystr[0:21:1]
print(mystr[0:21:1]) #Print full string mystr[0:21:1]
print(mystr[::1]) #Print full string mystr[0:21:1]
print(mystr[:10:3]) #Print 0 t0 10 and skip 2 charcters sequence
print(mystr[-20:-1]) #Print full string mystr[-20 to -1]
print(mystr[::-1]) #Reverse the string
print(mystr[::-2]) #Reverse the string and skip 1 character
sequence

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

+ It is known as concatenation operator used to join the


strings given either side of the operator.
* It is known as repetition operator. It concatenates the
multiple copies of the same string.
[] It is known as slice operator. It is used to access the
sub-strings of a particular string.
Python tutorial

[:] It is known as range slice operator. It is used to


access the characters from the specified range.
in It is known as membership operator. It returns if a
particular sub-string is present in the specified string.
not in It is also a membership operator and does the exact
reverse of in. It returns true if a particular substring is
not present in the specified string.
r/R It is used to specify the raw string. Raw strings are
used in the cases where we need to print the actual
meaning of escape characters such as "C://python".
To define any string as a raw string, the character r or
R is followed by the string.
% It is used to perform string formatting. It makes use of
the format specifiers used in C programming like %d
or %f to map their values in python. We will discuss
how formatting is done in python.

Example

Consider the following example to understand the real use of


Python operators.

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

print('w' in str) # prints false as w is not present in str


print('wo' not in str1) # prints false as wo is present in str1.

print(r'C://python37') # prints C://python37 as it is written


print("The string str : %s"%(str)) # prints The string str : Hello

Output:

HelloHelloHello
Hello world
o
ll
False
False
C://python37
The string str : Hello

Python String Formatting


Escape Sequence
Let's suppose we need to write the text as - They said, "Hello
what's going on?"- the given statement can be written in single
quotes or double quotes but it will raise the SyntaxError as it
contains both single and double-quotes.

Example

Consider the following example to understand the real use of


Python operators.

str = "They said, "Hello what's going on?""


Python tutorial

print(str)

Output:

SyntaxError: invalid syntax

We can use the triple quotes to accomplish this problem but


Python provides the escape sequence.

The backslash(/) symbol denotes the escape sequence. The


backslash can be followed by a special character and it interpreted
differently. The single quotes inside the string must be escaped.
We can apply the same as in the double quotes.

Example -

# using triple quotes


print('''''They said, "What's there?"''')

# escaping single quotes


print('They said, "What\'s going on?"')

# escaping double quotes


print("They said, \"What's going on?\"")

Output:

They said, "What's there?"


They said, "What's going on?"
They said, "What's going on?"

The format() method


Python tutorial

The format() method is the most flexible and useful method in


formatting strings. The curly braces {} are used as the placeholder
in the string and replaced by the format() method argument. Let's
have a look at the given an example:

Example 1:

# Using Curly braces


print("{} and {} both are the best friend".format("Devansh","
Abhishek"))

#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:

Devansh and Abhishek both are the best friend


Rohit and Virat best players
James,Peter,Ricky

Example 2:

name = "My name is {} and I am learning {}".format("Hariom",


"Python")
print(name)

name = "My name is {0} and I am learning {1}".format("Hariom",


"Python")
Python tutorial
print(name)

name = "My name is {a} and I am learning {b}".format(a =


"Hariom", b = "Python")
print(name)

name = "My name is {a:^20} and I am learning


{b:^15}".format(a = "Hariom", b = "Python")
print(name)

name = "My name is {a:20} and I am learning {b:15}".format(a =


"Hariom", b = "Python")
print(name)

name = "My name is {a:>20} and I am learning


{b:<15}".format(a = "Hariom", b = "Python")
print(name)

Output:

My name is Hariom and I am learning Python


My name is Hariom and I am learning Python
My name is Hariom and I am learning Python
My name is Hariom and I am learning Python
My name is Hariom and I am learning Python
My name is Hariom and I am learning Python

Python String Formatting Using % Operator


Integer = 10;
Float = 1.290
String = "Devansh"
print("Hi I am Integer ... My value is %d\nHi I am float ... My v
alue is %f\nHi I am string ... My value is %s"%
Python tutorial

(Integer,Float,String))

Output:

Hi I am Integer ... My value is 10


Hi I am float ... My value is 1.290000
Hi I am string ... My value is Devansh

Python String functions


Python provides various in-built functions that are used for string
handling.

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:

str1 = "hariom is a good boy"


str2 = "Hariomisagoodboy"

#Return true if str1 is a alfanumeric else return false


print(str1.isalnum()) #Return false because there are spaces in
Python tutorial
string
print(str2.isalnum()) #Return true because there are no spaces
in string

print(str1.endswith("boy")) #Return true because given string is


ending from boy
print(str1.count("i")) #Count that how many i are presents in
given string
print(str1.capitalize()) #Capitalize first character of given string
print(str1.find("is")) #Find given values/string and return its
index
print(str1.upper()) #Change all characters in uppercase of given
string
print(str2.lower()) #Change all characters in lowercase of given
string
print(str1.replace("hariom", "Hariom Singh Rajput")) #Replace a
string to another

Output:

False
True
True
2
Hariom is a good boy
7
HARIOM IS A GOOD BOY
hariomisagoodboy

Hariom Singh Rajput is a good boy

chr() and ord() functions of string:


python chr() function:
This takes an integer i and converts it to a character c according to
Python tutorial

ASCII value, so it returns a character string.

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

This is the ASCII value of C

<class 'str'>

Python ord() function:


This takes a single Unicode character (string of length 1) and
returns it’s ASCII value.

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: @

The ASCII value of this character is 64


Python tutorial

<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]

[10, 76, 30, 34, 9, 2, 4, 12]

Characteristics of Lists
The list has the following characteristics:

o The lists are ordered.


o The element of the list can access by index.
o The lists are the mutable type.

A list can store the number of various elements.

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

List indexing and splitting


The indexing is processed in the same way as it happens with the strings. The elements
of the list can be accessed by using the slice operator [].

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)

o The start denotes the starting index position of the list.


o The stop denotes the last index position of the list.
o The step is used to skip the nth element within a start:stop
Python tutorial

Consider the following example:

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]

[21, 54, 2, 54, 87, 12, 9, 2, 5, 3, 9]

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

Convert string into a list:


Example:
n = input("Enter a string: ")

# For a single string


l1 = n.split()
print("Your First List Is: ", l1)

l2 = []
# For a multiple string
for a in range(1, 6):
m = input("Enter sting " + str(a) + "--> ")
l2.append(m)

print("\nYour Second List Is: ", l2)

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

Your Second List Is: ['Red', 'Blue', 'Green', 'Yellow', 'Pink']


Python List functions:
Python provides the following built-in functions, which can be used with the lists.
Example:
numbers = [56, 32, 98, 2, 98, 5, 1, 21, 32, 14, 5, 7, 9, 10]
Python tutorial
print("Original list is", numbers)
numbers.reverse()
print("Reverse list is", numbers)
print("Length of list is: ", len(numbers))
print("Maximum number of list is: ", max(numbers))
print("Minimum number of list is: ", min(numbers))
numbers.append(100) #Insert element in last of the list
numbers.append(76)
print("After append: ", numbers)
numbers.insert(2, 55)
numbers.insert(3, 5)
numbers.insert(0, 66)
print("After insert:", numbers)
numbers.sort()
print("Sorted list is: ", numbers)
numbers.remove(5)
numbers.remove(10)
numbers.remove(100)
print("After remove: ", numbers)
numbers.pop() #Remove last element of the list
numbers.pop()
numbers.pop()
print("After pop: ", numbers)
Output:
Original list is [56, 32, 98, 2, 98, 5, 1, 21, 32, 14, 5, 7, 9, 10]
Reverse list is [10, 9, 7, 5, 14, 32, 21, 1, 5, 98, 2, 98, 32, 56]
Length of list is: 14
Maximum number of list is: 98
Minimum number of list is: 1
After append: [10, 9, 7, 5, 14, 32, 21, 1, 5, 98, 2, 98, 32, 56, 100, 76]
After insert: [66, 10, 9, 55, 5, 7, 5, 14, 32, 21, 1, 5, 98, 2, 98, 32, 56, 100, 76]
Sorted list is: [1, 2, 5, 5, 5, 7, 9, 10, 14, 21, 32, 32, 55, 56, 66, 76, 98, 98, 100]
After remove: [1, 2, 5, 5, 7, 9, 14, 21, 32, 32, 55, 56, 66, 76, 98, 98]
After pop: [1, 2, 5, 5, 7, 9, 14, 21, 32, 32, 55, 56, 66]

List Comprehension Elegant way to create lists:


 List comprehension is an elegant way to define and create lists based on existing lists.
 List comprehension is generally more compact and faster than normal functions and loops for
creating lists.

Syntax for list comprehension:


[expression for item in list]

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)

# Creating a list by using list comprehension


print("\nCreating list by using list comprehension...")
n = [m for m in range(1, 11)]
print(n)
Python tutorial
# Give a condition by using list comprehension
print("\nEven numbers are...")
x = [y for y in range(1, 21) if y%2 == 0]
print(x)

# Convert a string into list by using list comprehension


Str = "WELL-COME BACK"
b = [a for a in Str]
print("\nGiven string in list is..")
print(b)

Output:
Creating list by using for loop...
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

Creating list by using list comprehension...


[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

Even numbers are...


[2, 4, 6, 8, 10, 12, 14, 16, 18, 20]

Given string in list is..


['W', 'E', 'L', 'L', '-', 'C', 'O', 'M', 'E', ' ', 'B', 'A', 'C', 'K']
Iterate more than one lists at once:
We can iterate more than one lists at once by using for loop, but number of elements should be equal in
every lists.
Example:
l1 = [10, 20, 30, 40, 45, 50]
l2 = [5, 9, 8, 2, 10, 89]
l3 = [20, 40, 60, 80, 100, 49]

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

We can also iterate many lists at once by using zip() function.


zip() function in python:
we can iterate more than one list at once by using zip() function in place of range() function, but number of
elements should be equal in all lists otherwise it will iterate minimum number of elements which are
available in any list.
Python tutorial
Example:
l1 = [10, 20, 30, 40, 45, 50]
l2 = [5, 9, 8, 2, 10, 89, 1]
l3 = [20, 40, 60, 80, 100]

for a, b, c in zip(l1, l2, l3):


print(a, b, c)
Output:
10 5 20
20 9 40
30 8 60
40 2 80

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.

1. T1 = (101, "Peter", 22)


2. T2 = ("Apple", "Banana", "Orange")
3. T3 = 10,20,30,40,50
4.
5. print(type(T1))
6. print(type(T2))
7. print(type(T3))

Output:

<class 'tuple'>
<class 'tuple'>
<class 'tuple'>

Example - 2

1. tuple1 = tuple(input("Enter the tuple elements ..."))


Python tutorial

2. print(tuple1)

3. count = 0

4. for i in tuple1:

5. print("tuple1[%d] = %s"%(count, i))

6. count = count+1

Output:

Enter the tuple elements ...123456


('1', '2', '3', '4', '5', '6')
tuple1[0] = 1
tuple1[1] = 2
tuple1[2] = 3
tuple1[3] = 4
tuple1[4] = 5
tuple1[5] = 6

Tuple indexing and slicing


The indexing and slicing in the tuple are similar to lists. The indexing in the tuple starts
from 0 and goes to length(tuple) - 1.

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

Consider the following example:

1. tup = (1,2,3,4,5,6,7)

2. print(tup[0])

3. print(tup[1])

4. print(tup[2])

5. # It will give the IndexError

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

element outside of tuple that raised an IndexError.

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])

8. # element 0 to 6 and take step of 2

9. print(tuple[0:6:2])

Output:

(2, 3, 4, 5, 6, 7)
(1, 2, 3, 4)
(1, 2, 3, 4)
(1, 3, 5)

Basic Operations of tupples:


T1 = (2, 4, 6, 7, 5)
T2 = (1, 5, 9, 2, 0)
print(T1+T2) #Appending
print(2*T1) #Repetition
print(6 in T1)

Output:
(2, 4, 6, 7, 5, 1, 5, 9, 2, 0)
(2, 4, 6, 7, 5, 2, 4, 6, 7, 5)

True

List vs. Tuple


SN List Tuple

1 The literal syntax of list is shown by the []. The literal syntax of the tuple is shown by the ().

2 The List is mutable. The tuple is immutable.

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.

o Keys must be a single element


o Value can be any type such as list, tuple, integer, etc.

Example:

D1 = {"Hariom":"Blue","Abhishek":"Red", "Pooja":"Pink", "Harish":"Green",


"Sahil":"Orange"}
print(D1)
print("favorite color of Hariom is:", D1["Hariom"])
print("favorite color of Pooja is:" ,D1["Pooja"])
D1["Rahul"] = "Yellow"
D1["Nitin"] = "Black"
del D1["Sahil"]
print(D1,"\n")

D2 = {"Hariom":"Samosa",
"Raj":{"Brake fast":"Breade", "Lunch":"Roti", "Dinner":"Halwa"},
"Abhishek":"Kachori",
"Pooja":"Jalebi",
"Harish":"Hot dog", "Sahil":"Sigrate"}

print("Raj follow the Following schedule: ", D2["Raj"])


print("Raj will eat in lunch: ", D2["Raj"]["Lunch"])
Output:

{'Hariom': 'Blue', 'Abhishek': 'Red', 'Pooja': 'Pink', 'Harish': 'Green', 'Sahil': 'Orange'}

favorite color of Hariom is: Blue


Python tutorial

favorite color of Pooja is: Pink

{'Hariom': 'Blue', 'Abhishek': 'Red', 'Pooja': 'Pink', 'Harish': 'Green', 'Rahul': 'Yellow',
'Nitin': 'Black'}

Raj follow the Following schedule: {'Brake fast': 'Breade', 'Lunch': 'Roti', 'Dinner':
'Halwa'}

Raj will eat in lunch: Roti

Creating the dictionary


The dictionary can be created by using multiple key-value pairs enclosed with the curly
brackets {}, and each key is separated from its value by the colon (:).The syntax to
define the dictionary is given below.

Syntax:

1. Dict = {"Name": "Tom", "Age": 22}

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.

1. # Creating an empty Dictionary

2. Dict = {}

3. print("Empty Dictionary: ")

4. print(Dict)

5.

6. # Creating a Dictionary

7. # with dict() method

8. Dict = dict({1: 'Hariom', 2: 'Raj', 3:'Pooja'})

9. print("\nCreate Dictionary by using dict(): ")


Python tutorial

10. print(Dict)

11.

12. # Creating a Dictionary

13. # with each item as a Pair

14. Dict = dict([(1, 'Devansh'), (2, 'Sharma')])

15. print("\nDictionary with each item as a pair: ")

16. print(Dict)

Output:

Empty Dictionary:
{}

Create Dictionary by using dict():


{1: 'Hariom', 2: 'Raj', 3: 'Pooja'}

Dictionary with each item as a pair:


{1: 'Devansh', 2: 'Sharma'}

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

1. Employee = {"Name": "John", "Age": 29, "salary":25000,"Company":"GOOGLE"}

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

1. Employee = {"Name": "John", "Age": 29, "salary":25000,"Company":"GOOGLE"}

2. for x in Employee:

3. print(Employee[x])

Output:

John
29
25000

Properties of Dictionary keys


1. In the dictionary, we cannot store multiple values for the same keys. If we pass more
than one value for a single key, then the value which is last assigned is considered as the
value of the key.

Consider the following example.

1. Employee={"Name":"John","Age":29,"Salary":25000,"Company":"GOOGLE","Name"
:"John"}

2. for x,y in Employee.items():

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.

Consider the following example.

1. Employee = {"Name": "John", "Age": 29, "salary":25000,"Company":"GOOGLE",


Python tutorial

[100,201,301]:"Department ID"}

2. for x,y in Employee.items():

3. print(x,y)

Output:

Traceback (most recent call last):


File "dictionary.py", line 1, in
Employee = {"Name": "John", "Age": 29, "salary":25000,"Company":"GOOGLE",
[100,201,301]:"Department ID"}
TypeError: unhashable type: 'list'
Built-in Functions and Methods In Dictionary:

Python includes the following dictionary functions −

Sr.N Function with Description


o

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.

Python includes following dictionary methods –


Python tutorial

Sr.No Methods with Description

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

Sr.No Methods with Description

Returns list of dictionary dict’s values

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

Example 1: Using curly braces

1. Days = {"Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Su


nday"}

2. print(Days)

3. print(type(Days))

4. print("looping through the set elements ... ")

5. for i in Days:

6. print(i)

Output:

{'Friday', 'Tuesday', 'Monday', 'Saturday', 'Thursday', 'Sunday', 'Wednesday'}


<class 'set'>
looping through the set elements ...
Friday
Tuesday
Monday
Saturday
Thursday
Sunday
Wednesday
Basic operations on set:
s1 = set([1, 3, 2, 5, 72, 9, 10, 4, 3]) # This is first way to create a set
s2 = {38, 98, 76, 1, 34, 45, 4, 87} # This is second way to create a set
print("Type of s1 is: ", type(s1))
print("Type of s2 is: ", type(s2))

print("\nBefore update s1: ", s1)

# Update the set by adding some new elements


s1.update([12, 34, 76])
s1.update(s2)

print("After update s1: ", s1)

# Delete some elements from the set

# If element not exist in set than it will not throw error


s1.discard(72)
s1.discard(34)
# If element not exist in set than it will throw an error
s1.remove(3)
s1.remove(87)
# The pop() function will randomlly delete element from the set
print("Popped element is: ", s1.pop())
print("Popped element is: ", s1.pop())
print("Popped element is: ", s1.pop())
Python tutorial
print("After Delete some element, s1: ", s1)

print("Length of s1 is: ", len(s1))


print("Max element of s1 is: ", max(s1))
print("Min element of s1 is: ", min(s1))
print(s1.isdisjoint(s2))

print("Elements of s2 are: ", s2)


# Adding new elements in s2
s2.add(4)
s2.add(5)

print("Now Elements of s2 are: ", s2)

# Remove all elements from set s2


s2.clear()
print("After clear s2 is: ", s2)

Output:
Type of s1 is: <class 'set'>
Type of s2 is: <class 'set'>

Before update s1: {1, 2, 3, 4, 5, 72, 9, 10}


After update s1: {1, 2, 3, 4, 5, 72, 9, 10, 12, 76, 87, 34, 98, 38,
45}
Popped element is: 1
Popped element is: 2
Popped element is: 4
After Delete some element, s1: {5, 9, 10, 12, 76, 98, 38, 45}
Length of s1 is: 8
Max element of s1 is: 98
Python tutorial

Min element of s1 is: 5


False
Elements of s2 are: {1, 98, 34, 4, 38, 76, 45, 87}
Now Elements of s2 are: {1, 98, 34, 4, 5, 38, 76, 45, 87}
After clear s2 is: set()
Difference between discard() and remove()
Despite the fact that discard() and remove() method both perform the same task,
There is one main difference between discard() and remove().

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.

Python Set Operations


Set can be performed mathematical operation such as union, intersection, difference,
and symmetric difference. Python provides the facility to carry out these operations with
operators or methods. We describe these operations as follows.

Union of two Sets


The union of two sets is calculated by using the pipe (|) operator. The union of the two
sets contains all the items that are present in both the sets.
Python tutorial

Consider the following example to calculate the union of two sets.

Example 1: using union | operator

1. Days1 = {"Monday","Tuesday","Wednesday","Thursday", "Sunday"}

2. Days2 = {"Friday","Saturday","Sunday"}

3. print(Days1|Days2) #printing the union of the sets

Output:

{'Friday', 'Sunday', 'Saturday', 'Tuesday', 'Wednesday', 'Monday', 'Thursday'}

Python also provides the union() method which can also be used to calculate the union
of two sets. Consider the following example.

Example 2: using union() method

1. Days1 = {"Monday","Tuesday","Wednesday","Thursday"}

2. Days2 = {"Friday","Saturday","Sunday"}

3. print(Days1.union(Days2)) #printing the union of the sets

Output:

{'Friday', 'Monday', 'Tuesday', 'Thursday', 'Wednesday', 'Sunday', 'Saturday'}


Python tutorial

Intersection of two sets


The intersection of two sets can be performed by the and & operator or
the intersection() function. The intersection of the two sets is given as the set of the
elements that common in both sets.

Consider the following example.

Example 1: Using & operator

1. Days1 = {"Monday","Tuesday", "Wednesday", "Thursday"}

2. Days2 = {"Monday","Tuesday","Sunday", "Friday"}

3. print(Days1&Days2) #prints the intersection of the two sets

Output:

{'Monday', 'Tuesday'}

Example 2: Using intersection() method

1. set1 = {"Devansh","John", "David", "Martin"}

2. set2 = {"Steve", "Milan", "David", "Martin"}

3. print(set1.intersection(set2)) #prints the intersection of the two sets


Python tutorial

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}

The intersection_update() method


The intersection_update() method removes the items from the original set that are not
present in both the sets (all the sets if more than one are specified).

The intersection_update() method is different from the intersection() method since it


modifies the original set by removing the unwanted items, on the other hand, the
intersection() method returns a new set.

Consider the following example.

1. a = {"Devansh", "bob", "castle"}

2. b = {"castle", "dude", "emyway"}

3. c = {"fuson", "gaurav", "castle"}

4.

5. a.intersection_update(b, c)

6.

7. print(a)

Output:
Python tutorial
{'castle'}

Difference between the two sets


The difference of two sets can be calculated by using the subtraction (-) operator
or intersection() method. Suppose there are two sets A and B, and the difference is A-B
that denotes the resulting set will be obtained that element of A, which is not present in
the set B.

Consider the following example.

Example 1 : Using subtraction ( - ) operator

1. Days1 = {"Monday", "Tuesday", "Wednesday", "Thursday"}

2. Days2 = {"Monday", "Tuesday", "Sunday"}

3. print(Days1-Days2) #{"Wednesday", "Thursday" will be printed}

Output:

{'Thursday', 'Wednesday'}

Example 2 : Using difference() method

1. Days1 = {"Monday", "Tuesday", "Wednesday", "Thursday"}

2. Days2 = {"Monday", "Tuesday", "Sunday"}

3. print(Days1.difference(Days2)) # prints the difference of the two sets Days1 and D


Python tutorial

ays2

Output:

{'Thursday', 'Wednesday'}

Symmetric Difference of two sets


The symmetric difference of two sets is calculated by ^ operator
or symmetric_difference() method. Symmetric difference of sets, it removes that
element which is present in both sets. Consider the following example:

Example - 1: Using ^ operator

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}

Example - 2: Using symmetric_difference() method

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.

Consider the following example.

1. Days1 = {"Monday", "Tuesday", "Wednesday", "Thursday"}

2. Days2 = {"Monday", "Tuesday"}

3. Days3 = {"Monday", "Tuesday", "Friday"}

4.

5. #Days1 is the superset of Days2 hence it will print true.

6. print (Days1>Days2)

7.

8. #prints false since Days1 is not the subset of Days2

9. print (Days1<Days2)

10.

11. #prints false since Days2 and Days3 are not equivalent

12. print (Days2 == Days3)

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.

Consider the following example to create the frozen set.

1. Frozenset = frozenset([1,2,3,4,5])

2. print(type(Frozenset))

3. print("\nprinting the content of frozen set...")

4. for i in Frozenset:

5. print(i);

6. Frozenset.add(6) #gives an error since we cannot change the content of Frozenset


after creation

Output:

<class 'frozenset'>

printing the content of frozen set...


1
2
3
4
5
Traceback (most recent call last):
File "set.py", line 6, in <module>
Frozenset.add(6) #gives an error since we can change the content of Frozenset after
creation
AttributeError: 'frozenset' object has no attribute 'add'
Python tutorial

Frozenset for the dictionary


If we pass the dictionary as the sequence inside the frozenset() method, it will take only
the keys from the dictionary and returns a frozenset that contains the key of the
dictionary as its elements.

Consider the following example.

1. Dictionary = {"Name":"John", "Country":"USA", "ID":101}

2. print(type(Dictionary))

3. Frozenset = frozenset(Dictionary); #Frozenset will contain the keys of the dictionar


y

4. print(type(Frozenset))

5. for i in Frozenset:

print(i)

Output:

<class 'dict'>
<class 'frozenset'>
Name
Country
ID

Python Built-in set methods:

Python contains the following methods to be used with the sets.

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.

2 clear() It deletes all the items from the set.

3 copy() It returns a shallow copy of the set.

4 difference_update(....) It modifies this set by removing all the items that are also present in the specified
sets.

5 discard(item) It removes the specified item from the set.


Python tutorial
6 intersection() It returns a new set that contains only the common elements of both the sets. (all
the sets if more than two are specified).

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).

8 Isdisjoint(....) Return True if two sets have a null intersection.

9 Issubset(....) Report whether another set contains this set.

10 Issuperset(....) Report whether this set contains another set.

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.

15 union(....) Return the union of sets as a new set.


(i.e. all elements that are in either set.)

16 update() Update a set with the union of itself and others.

Python If-else statements


Decision making is the most important aspect of almost all the programming languages.
As the name implies, decision making allows us to run a particular block of code for a
particular decision. Here, the decisions are made on the validity of the particular
conditions. Condition checking is the backbone of decision making.

In python, decision making is performed by the following statements.

Statement Description

If The if statement is used to test a specific condition. If the condition is


Statement true, a block of code (if-block) will be executed.

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.

The syntax of the if-statement is given below.

1. if expression:

2. statement

Example:

1. num = int(input("enter the number?"))


Python tutorial

2. if num%2 == 0:

3. print("Number is even")

Output:

enter the number?10


Number is even

The if-else statement


The if-else statement provides an else block combined with the if statement which is
executed in the false case of the condition.

If the condition is true, then the if-block is executed. Otherwise, the else-block is
executed.
Python tutorial

The syntax of the if-else statement is given below.

1. if condition:

2. #block of statements

3. else:

4. #another block of statements (else-block)

Example : Program to check whether a person is eligible to vote or not.


Python tutorial

1. age = int (input("Enter your age? "))

2. if age>=18:

3. print("You are eligible to vote !!");

4. else:

5. print("Sorry! you have to wait !!");

Output:

Enter your age? 90


You are eligible to vote !!

The elif statement


The elif statement enables us to check multiple conditions and execute the specific block
of statements depending upon the true condition among them. We can have any number
of elif statements in our program depending upon our need. However, using elif is
optional.

The elif statement works like an if-else-if ladder statement in C. It must be succeeded by
an if statement.

The syntax of the elif statement is given below.

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:

11. # block of statements

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

Enter the marks? 80

You scored grade B + ...


‘in’ and ‘not in’ keywords:
list1 = ["Mango", "Apple", "Banana", "Orange", "Pineapple", "Papaya", "Grapes"]

if "Apple" in list1:
print("Apple is present in the list")
else:
print("Apple is not present in the list")

if "Guava" not in list1:


print("Guava is not present in the list")
else:
print("Guava is present in the list")

Output:
Apple is present in the list

Guava is not 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

Why we use loops in python?


The looping simplifies the complex problems into the easy ones. It enables us to alter the
flow of the program so that instead of writing the same code again and again, we can
repeat the same code for a finite number of times. For example, if we need to print the
first 10 natural numbers then, instead of using the print statement 10 times, we can print
inside a loop which runs up to 10 iterations.

Advantages of loops
There are the following advantages of loops in Python.

1. It provides code re-usability.


2. Using loops, we do not need to write the same code again and again.
3. Using loops, we can traverse over the elements of data structures (array or linked
lists).
Python tutorial

There are the following loop statements 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.

Python for loop


The for loop in Python is used to iterate the statements or a part of the program several
times. It is frequently used to traverse the data structures like list, tuple, or dictionary.

The syntax of for loop in python is given below.

1. for iterating_var in sequence:


2. statement(s)

The for loop flow chart


Python tutorial

For loop Using Sequence


Example-1: Iterating string using for loop

1. str = "Python"
2. for i in str:
3. print(i)

Output:

P
Python tutorial
y
t
h
o
n

Example- 2: Program to print the table of the given number .

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

Example-3: Program to print the sum of the given list.

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 sum is: 183

For loop Using range() function


The range() function

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)

o The start represents the beginning of the iteration.


o The stop represents that the loop will iterate till stop-1. The range(1,5) will
generate numbers 1 to 4 iterations. It is optional.
o The step size is used to skip the specific numbers from the iteration. It is optional to
use. By default, the step size is 1. It is optional.

Consider the following examples:

Example-1: Program to print numbers in sequence.

1. for i in range(10):
2. print(i,end = ' ')

Output:

0 1 2 3 4 5 6 7 8 9

Example - 2: Program to print table of given number.

1. n = int(input("Enter the number "))


2. for i in range(1,11):
3. c = n*i
4. print(n,"*",i,"=",c)

Output:

Enter the number 10


10 * 1 = 10
10 * 2 = 20
10 * 3 = 30
10 * 4 = 40
10 * 5 = 50
10 * 6 = 60
10 * 7 = 70
10 * 8 = 80
10 * 9 = 90
10 * 10 = 100

Example-3: Program to print even number using step size in range().


Python tutorial

1. n = int(input("Enter the number "))


2. for i in range(2,n,2):
3. print(i)

Output:

Enter the number 20


2
4
6
8
10
12
14
16
18

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

Nested for loop in python


Python allows us to nest any number of for loops inside a for loop. The inner loop is
executed n number of times for every iteration of the outer loop. The syntax is given
below.

Syntax

1. for iterating_var1 in sequence: #outer loop


2. for iterating_var2 in sequence: #inner loop
3. #block of statements
4. #Other statements
Python tutorial

Example- 1: Nested for loop

1. # User input for number of rows


2. rows = int(input("Enter the rows:"))
3. # Outer loop will print number of rows
4. for i in range(0,rows+1):
5. # Inner loop will print number of Astrisk
6. for j in range(i):
7. print("*",end = '')
8. print()

Output:

Enter the rows:5


*
**
***
****
*****

Example-2: Program to number pyramid.

1. rows = int(input("Enter the rows"))


2. for i in range(0,rows+1):
3. for j in range(i):
4. print(i,end = '')
5. print()

Output:

1
22
333
4444
55555

Using else statement with for loop


Unlike other languages like C, C++, or Java, Python allows us to use the else statement
with the for loop which can be executed only when all the iterations are exhausted. Here,
we must notice that if the loop contains any of the break statement then the else
Python tutorial

statement will not be executed.

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.

The 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!

Python While loop


The Python while loop allows a part of the code to be executed until the given condition
returns false. It is also known as a pre-tested loop.

It can be viewed as a repeating if statement. When we don't know the number of


iterations then the while loop is most effective to use.

The syntax is given below.

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.

While loop Flowchart


Python tutorial

Loop Control Statements


We can change the normal sequence of while loop's execution using the loop control
statement. When the while loop's execution is completed, all automatic objects defined in
that scope are demolished. Python offers the following control statement to use within
the while loop.

1. Continue Statement - When the continue statement is encountered, the control


transfer to the beginning of the loop.
Python tutorial
Example:

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

Do you want to continue printing the table, press 0 for no?1

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

Do you want to continue printing the table, press 0 for no?0

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.

Example- 1: Pass statement

values = {'P', 'y', 't', 'h','o','n'}


"""
for val in values:
# This is an empty loop that's why it will give an error
"""

for val in values:


pass

print("The code executed successfully")


Python tutorial

Output:

The code executed successfully

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

We can create empty class or function using the pass statement.

# Empty Function
def function_name(args):
pass
#Empty Class
class Python:
pass

Examples of while loop:

Example-1: Program to print 1 to 10 using while loop

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

Example -2: Program to print table of given numbers.


i=1
number = int(input("Enter the number:"))
while i<=10:
print("%d X %d = %d" %(number,i,number*i))
i = i+1

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

Using else with while loop


Example:
i=1
while(i<=5):
print(i)
i=i+1
else:
print("The while loop exhausted")

Output:
1
2
3
4
Python tutorial
5

The while loop exhausted

Infinite while loop


If the condition is given in the while loop never becomes false, then the while loop will
never terminate, and it turns into the infinite while loop.

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:

Hi! we are inside the infinite while loop


Hi! we are inside the infinite while loop

True keyword in while loop:


If we use true keyword in while loop than the loop never becomes false, but we can stop this loop by using some condition with the help
of if statement.

Example:

i = 0
while True:
if i <= 10:
i += 1
continue

print(i, end=" ")

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.

There are mainly two types of functions.

o User-define functions - The user-defined functions are those define by


the user to perform the specific task.
o Built-in functions - The built-in functions are those functions that are pre-
defined in Python.

Advantage of Functions in Python


There are the following advantages of Python 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

o However, Function calling is always overhead in a Python program.

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

The return statement


The return statement is used at the end of the function and returns the result of the
function. It terminates the function execution and transfers the result where the function
is called. The return statement cannot be used outside of the function.

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.

Consider the following example:

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:

The sum is: 30

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.

Example 2 Creating function without return statement

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:

1. #Python function to calculate the sum of two variables


2. #defining the function
3. def sum (a,b):
4. return a+b;
5.
6. #taking values from the user
7. a = int(input("Enter a: "))
8. b = int(input("Enter b: "))
9.
10. #printing the sum of a and b
11. print("Sum = ",sum(a,b))

Output:

Enter a: 10
Enter b: 20
Sum = 30

Call by reference in Python


In Python, call by reference means passing the actual value as an argument in the
function. All the functions are called by reference, i.e., all the changes made to the
reference inside the function revert back to the original value referred by the reference.

Example 1 Passing Immutable Object (List)

1. #defining the function


Python tutorial
2. def change_list(list1):
3. list1.append(20)
4. list1.append(30)
5. print("list inside function = ",list1)
6.
7. #defining the list
8. list1 = [10,30,40,50]
9.
10. #calling the function
11. change_list(list1)
12. print("list outside function = ",list1)

Output:

list inside function = [10, 30, 40, 50, 20, 30]


list outside function = [10, 30, 40, 50, 20, 30]

Example 2 Passing Mutable Object (String)

1. #defining the function


2. def change_string (str):
3. str = str + " Hows you "
4. print("printing the string inside function :",str)
5.
6. string1 = "Hi I am there"
7.
8. #calling the function
9. change_string(string1)
10.
11. print("printing the string outside function :",string1)

Output:

printing the string inside function : Hi I am there Hows you


printing the string outside function : Hi I am there

doc string of a function:


Python documentation strings (or docstrings) provide a
Python tutorial

convenient way of associating documentation with Python


modules, functions, classes, and methods.
It’s specified in source code that is used, like a comment, to
document a specific segment of code. Unlike conventional
source code comments, the docstring should describe what the
function does, not how.

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:

Enter the name: John


Hi John

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:

Enter the principle amount: 5000


Python tutorial
Enter the rate of interest: 5
Enter the time in years: 3
Simple Interest: 750.0

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:

My name is john and age is 22


My name is David and age is 10

Variable-length Arguments (*args)


In large projects, sometimes we may not know the number of arguments to be passed in
advance. In such cases, Python provides us the flexibility to offer the comma-separated
values which are internally treated as tuples at the function call. By using the variable-
length arguments, we can pass any number of arguments.

However, at the function definition, we define the variable-length argument using


the *args (star) as *<variable - name >.

Consider the following example.

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:

type of passed argument is <class 'tuple'>


printing the passed arguments...
john
David
smith
nick

Example 2:

def calculate(*args):
sum=0
for arg in args:
sum = sum +arg
print("The sum is",sum)

calculate(10,20,30,40) #100 will be printed as the sum

Output:

The sum is 100

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.

Consider the following example:

Example : Many arguments using Keyword argument


Python tutorial
1. def food(**kwargs):
2. print(kwargs)
3. food(a="Apple")
4. food(fruits="Orange", Vagitables="Carrot")

Output:

{'a': 'Apple'}
{'fruits': 'Orange', 'Vagitables': 'Carrot'}

Using *args and **kwargs to call a function:


Example:
def myFun(arg1, arg2, arg3):
print("First Name: ", arg1)
print("Middle Name: ", arg2)
print("Last Name: ", arg3)

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

Middle Name: Singh


Last Name: Rajput
Python Built-in Functions
The Python built-in functions are defined as the functions whose functionality is pre-
defined in Python. The python interpreter has several functions that are always present
for use. These functions are known as Built-in Functions.

Python abs() Function


The python abs() function is used to return the absolute value of a number. It takes only
one argument, a number whose absolute value is to be returned. The argument can be
an integer and floating-point number. If the argument is a complex number, then, abs()
returns its magnitude.

Python abs() Function Example

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:

Absolute value of -20 is: 20


Absolute value of -20.83 is: 20.83

Python bin() Function


The python bin() function is used to return the binary representation of a specified
integer. A result always starts with the prefix 0b.

Python bin() Function Example

1. x = 10
Python tutorial
2. y = bin(x)
3. print (y)

Output:

0b1010

Python format() Function


The python format() function returns a formatted representation of the given value.

Python format() Function Example

1. # d, f and b are a type


2.
3. # integer
4. print(format(123, "d"))
5.
6. # float arguments
7. print(format(123.4567898, "f"))
8.
9. # binary format
10. print(format(12, "b"))

Output:

123
123.456790
1100

Python iter() Function


The python iter() function is used to return an iterator object. It creates an object which
can be iterated one element at a time.

Python iter() Function Example

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

Python len() Function


The python len() function is used to return the length (the number of items) of an object.

Python len() Function Example

1. strA = 'Python'
2. print(len(strA))

Output:

6
Python tutorial

Python list()
The python list() creates a list in python.

Python list() Example

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.

Python complex() Example

1. # Python complex() function example


2. # Calling function
Python tutorial
3. a = complex(1) # Passing single parameter
4. b = complex(1,2) # Passing both parameters
5. # Displaying result
6. print(a)
7. print(b)

Output:

(1.5+0j)
(1.5+2.2j)

Python filter() Function


Python filter() function is used to get filtered elements. This function takes two
arguments, first is a function and the second is iterable. The filter function returns a
sequence of those elements of iterable object for which function returns true value.

The first argument can be none, if the function is not available and returns only elements
that are true.

Python filter() Function Example

1. # Python filter() function example


2. def filterdata(x):
3. if x>5:
4. return x
5. # Calling function
6. result = filter(filterdata,(1,2,6))
7. # Displaying result
8. print(list(result))

Output:

[6]

Python hash() Function


Python hash() function is used to get the hash value of an object. Python calculates the
hash value by using the hash algorithm. The hash values are integers and used to
Python tutorial

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.

Python hash() Function Example

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

Python min() Function


Python min() function is used to get the smallest element from the collection. This
function takes two arguments, first is a collection of elements and second is key, and
returns the smallest element from the collection.

Python min() Function Example

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.

Python set() Function Example

# 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'}

Python hex() Function


Python hex() function is used to generate hex value of an integer argument. It takes an
integer argument and returns an integer converted into a hexadecimal string. In case, we
want to get a hexadecimal value of a float, then use float.hex() function.

Python hex() Function Example

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

Python sorted() Function


Python sorted() function is used to sort elements. By default, it sorts elements in an
ascending order but can be sorted in descending also. It takes four arguments and
returns a collection in sorted order. In the case of a dictionary, it sorts only keys, not
values.

Python sorted() Function Example

str = "Hariom_Singh Rajput-@12345" # declaring string


# Calling function
sorted1 = sorted(str) # sorting string
# Displaying result
print(sorted1)

Output:
[' ', '-', '1', '2', '3', '4', '5', '@', 'H', 'R', 'S', '_', 'a', 'a', 'g', 'h', 'i', 'i', 'j',
'm', 'n', 'o', 'p', 'r', 't', 'u']

Python next() Function


Python next() function is used to fetch next item from the collection. It takes two
arguments, i.e., an iterator and a default value, and returns an element.

This method calls on iterator and throws an error if no item is present. To avoid the error,
we can set a default value.

Python next() Function Example

1. number = iter([256, 32, 82]) # Creating iterator


2. # Calling function
3. item = next(number)
4. # Displaying result
5. print(item)
6. # second item
7. item = next(number)
8. print(item)
Python tutorial
9. # third item
10. item = next(number)
11. print(item)

Output:

256
32
82

Python input() Function


Python input() function is used to get an input from the user. It prompts for the user
input and reads a line. After reading data, it converts it into a string and returns it.

Python input() Function Example

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

Python oct() Function


Python oct() function is used to get an octal value of an integer number. This method
takes an argument and returns an integer converted into an octal string. It throws an
error TypeError, if argument type is other than an integer.

Python oct() function Example

1. # Calling function
2. val = oct(10)
3. # Displaying result
4. print("Octal value of 10:",val)
Python tutorial

Output:

Octal value of 10: 0o12

Python ord() Function


The python ord() function returns an integer representing Unicode code point for the
given Unicode character.

Python ord() function Example

1. # Code point of an integer


2. print(ord('8'))
3.
4. # Code point of an alphabet
5. print(ord('R'))
6.
7. # Code point of a character
8. print(ord('&'))

Output:

56
82
38

Python pow() Function


The python pow() function is used to compute the power of a number. It returns x to the
power of y. If the third argument(z) is given, it returns x to the power of y modulus z, i.e.
(x, y) % z.

Python pow() function Example

1. # positive x, positive y (x**y)


2. print(pow(4, 2))
3.
4. # negative x, positive y
Python tutorial
5. print(pow(-4, 2))
6.
7. # positive x, negative y (x**-y)
8. print(pow(4, -2))
9.
10. # negative x, negative y
11. print(pow(-4, -2))

Output:

16
16
0.0625
0.0625

Python range() Function


The python range() function returns an immutable sequence of numbers starting from 0
by default, increments by 1 (by default) and ends at a specified number.

Python range() function Example

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]

Python reversed() Function


Python tutorial

The python reversed() function returns the reversed iterator of the given sequence.

Python reversed() function Example

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:

['a', 'v', 'a', 'J']


['a', 'v', 'a', 'J']
[11, 10, 9, 8]
[5, 7, 2, 1]

Python round() Function


The python round() function rounds off the digits of a number and returns the floating
point number.

Python round() Function Example

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.

Python str() Function Example

1. str('4')

Output:

'4'

Python tuple() Function


The python tuple() function is used to create a tuple object.

Python tuple() Function Example

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)

and many more built-in functions are available in python.

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.

Advantages of using recursion


 A complicated function can be split down into smaller sub-
problems utilizing recursion.
 Sequence creation is simpler through recursion than
utilizing any nested iteration.
 Recursive functions render the code look simple and
effective.
Disadvantages of using recursion
 A lot of memory and time is taken through recursive calls
which makes it expensive for use.
Python tutorial
 Recursive functions are challenging to debug.
 The reasoning behind recursion can sometimes be tough to
think through.
Example1:
def factorial(n):
"""
This a iterative method for factorial of a number
"""
fac = 1
for i in range(n):
fac = fac * (i+1)
return fac

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)

number = int(input("Enter a number: "))

print("Factorial using iterative method:")


print("Factorial of", number, "is:", factorial(number))

print("\nFactorial using recursive method:")


print("Factorial of", number, "is:", factorial_recursive(number))

Output:
Enter a number: 6
Factorial using iterative method:
Factorial of 6 is: 720

Factorial using recursive method:


Factorial of 6 is: 720
Python tutorial

Example2:
def febonacci(n):
if n == 0:
return 0
elif n == 1:
return 1
else:
return febonacci(n-1) + febonacci(n-2)

number = int(input("Enter a number: "))


# print(number, "th index is of fibonacci series is:", febonacci(number))

print("Your fibonacci series is:")


for i in range(number):
print(febonacci(i), end=" ")

Output:
Enter a number: 10
Your fibonacci series is:
0 1 1 2 3 5 8 13 21 34

Python Lambda Functions


Python Lambda function is known as the anonymous function that is defined without a
name. Python allows us to not declare the function in the standard manner, i.e., by using
the def keyword. Rather, the anonymous functions are declared by using
the lambda keyword. However, Lambda functions can accept any number of arguments,
but they can return only one value in the form of expression.

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.

The syntax to define an anonymous function is given below.

Syntax

1. lambda arguments: expression


Python tutorial

It can accept any number of arguments and has only one expression. It is useful when
the function objects are required.

Consider the following example of the lambda function.

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

x = float(input("Enter first number:"))


y = float(input("Enter second number:"))
print("Addition of", x, "and", y, "is:", add(x, y))
print("Subtraction of", x, "and", y, "is:", minus(x, y))
print("Multiplication of", x, "and", y, "is:", product(x, y))
print("Division of", x, "and", y, "is:", divide(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.

1. ZeroDivisionError: Occurs when a number is divided by zero.


2. NameError: It occurs when a name is not found. It may be local or global.
3. IndentationError: If incorrect indentation is given.
4. IOError: It occurs when Input Output operation fails.
5. EOFError: It occurs when the end of the file is reached, and yet operations are
being performed.

The problem without handling exceptions


Suppose we have two variables a and b, which take the input from the user and perform
the division of these values. What if the user entered the zero as the denominator? It will
interrupt the program execution and through a ZeroDivision exception. Let's see the
following example.

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.

Exception handling in python


The try-expect statement
If the Python program contains suspicious code that may throw the exception, we must
place that code in the try block. The try block must be followed with
the except statement, which contains a block of code that will be executed if there is
some exception in the try block.

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

Consider the following example.

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

Consider the following program.

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'>

The except statement using with exception variable


We can use the exception variable with the except statement. It is used by using
the as keyword. this object will return the cause of the exception. Consider the following
example:

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:

File not found

The try...finally block


Python provides the optional finally statement, which is used with the try statement. It
is executed no matter what exception occurs and used to release the external resource.
The finally block provides a guarantee of the execution.

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.

The syntax to use the finally block is given below.

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

execution of the program.

The syntax to use the raise statement is given below.

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:

Enter the age:17


The age is not valid

Example 2 Raise the exception with message

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:

Enter a positive integer: -5


That is a negative number!

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.")

age = int(input("How old are you? : "))


if age == 0:
raise ZeroDivisionError("Age can not be 0")

except ValueError as e:
print(e)

except Exception as e:
print(e)

except ZeroDivisionError as e:
print(e)

if name == "Hariom" or name == "hariom" or name == 'HARIOM':


print("Gate Out...")
else:
print(f"Hello {name}")

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")

print(f"Well come {name}")

info = input("Enter a key: ")

if info not in dict1:


raise KeyError("Key is not available in the dictionary")
else:
print(info, " = ", dict1[info])

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'

Python File Handling


The file handling plays an important role when the data needs to be stored permanently into the
file. A file is a named location on disk to store related information. We can access the stored
information (non-volatile) after the program termination.

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.

Hence, a file operation can be done in the following order.

o Open a file
o Read or write - Performing operation
Python tutorial

o Close the file

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:

1. file object = open(<file-name>, <access-mode>, <buffering>)

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.

5 w It opens the file to write only. It overwrites the file if previously


exists or creates a new one if no file exists with the same name.
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")

print("\n Reading in text mode:")


content = f.read(5) # it will read 5 characters from starting of a file
print(content)
content = f.read(5) # it will read next 5 characters from a file
print(content)

content = f.read() # it will read all content from file


print(content)

f.close()

print("\n Reading in binary mode:")


read2 = open("Hsr.txt", "rb")
content = read2.read()
print(content)

read2.close()

Output:
Reading in text mode:
Akkad
Bakk
Python tutorial

ad Bambe Bo
80 90 pure 100
What is this! Do you know...

Reading in binary mode:


b'Akkad Bakkad Bambe Bo\r\n80 90 pure 100\r\nWhat is this!
Do you know...\r\n'
The close() method
Once all the operations are done on the file, we must close it through our Python script
using the close() method. Any unwritten information gets destroyed once
the close() method is called on a file object.

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.

The syntax to use the close() method is given below.

Syntax

1. fileobject.close()

Consider the following example.

1. # opens the file file.txt in read mode


2. fileptr = open("file.txt","r")
3.
4. if fileptr:
5. print("file is opened successfully")
6.
Python tutorial
7. #closes the opened file
8. fileptr.close()

The with statement


The with statement was introduced in python 2.5. The with statement is useful in the
case of manipulating the files. It is used in the scenario where a pair of statements is to
be executed with a block of code in between.

The syntax to open a file using with the statement is given below.

1. with open(<file name>, <access mode>) as <file-pointer>:


2. #statement suite

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

print("\nReading another file\n")


with open("Hariom2.txt") as F:
data = F.read()
print(data)

Writing the file


To write some text to a file, we need to open the file using the open method with one of
the following access modes.

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

Read Lines of the file


Python facilitates to read the file line by line by using a function readline() method.
The readline() method reads the lines of the file from the beginning, i.e., if we use the
readline() method two times, then we can get the first two lines 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 = open("Hsr.txt", "r")


print("\nReading file line by line by using readline function:")
print(read2.readline())
print(read2.readline())

read2.close()

Read character by character:


Example:
read = open("Hsr.txt")
characters = read.read()

for i in characters:
print(i, end=" ")
Python tutorial

File Pointer positions


Python provides the tell() method which is used to print the byte number at which the file
pointer currently exists.

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

Modifying file pointer position


In real-world applications, sometimes we need to change the file pointer location
externally since we may need to read or write the content at various locations.

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!

The file related methods


The file object provides the following methods to manipulate the files on various
operating systems.

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.

2 File.fush() It flushes the internal buffer.

3 File.fileno() It returns the file descriptor used by the underlying


implementation to request I/O from the OS.

4 File.isatty() It returns true if the file is connected to a TTY device,


otherwise returns false.

5 File.next() It returns the next line from the file.

6 File.read([size]) It reads the file for the specified size.

7 File.readline([size]) It reads one line from the file and places the file pointer
to the beginning of the new line.

8 File.readlines([sizeh It returns a list containing all the lines of the file. It


int]) reads the file until the EOF occurs using readline()
function.

9 File.seek(offset[,fro It modifies the position of the file pointer to a specified


m) offset with the specified reference.

10 File.tell() It returns the current position of the file pointer within


the file.

11 File.truncate([size]) It truncates the file to the optional specified size.

12 File.write(str) It writes the specified string to a file

13 File.writelines(seq) It writes a sequence of the strings to a file.

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.

Renaming the file


The Python os module enables interaction with the operating system. The os module
provides the functions that are involved in file processing operations like renaming,
deleting, etc. It provides us the rename() method to rename the specified file to a new
Python tutorial

name. The syntax to use the rename() method is given below.

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:

The above code renamed current file2.txt to file3.txt

Removing the file


The os module provides the remove() method which is used to remove the specified file.
The syntax to use the remove() method is given below.

1. remove(file-name)

Example 1

1. import os;
2. #deleting the file named file3.txt
3. os.remove("file3.txt")

Creating the new directory


The mkdir() method is used to create the directories in the current working directory.
The syntax to create the new directory is given below.

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")

The getcwd() method


This method returns the current working directory.

The syntax to use the getcwd() method is given below.

Syntax

1. os.getcwd()

Example

1. import os
2. os.getcwd()

Output:

'C:\\Users\\DEVANSH SHARMA'

Changing the current working directory


The chdir() method is used to change the current working directory to a specified
directory.

The syntax to use the chdir() method is given below.

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.

The syntax to use the rmdir() method is given below.

Syntax

1. os.rmdir(directory name)

Example 1

1. import os
2. #removing the new directory
3. os.rmdir("directory_name")

It will remove the specified directory.

os.path.exists(): This method will check whether a file exists or


not by passing the name of the file as a parameter.
Example:
import os
#importing os module

result = os.path.exists("file_name") #giving the name of the file as a


parameter.

print(result)

Output
False
Python tutorial

os.path.getsize(): In this method, python will give us the size


of the file in bytes. To use this method we need to pass the
name of the file as a parameter.
Example:
import os #importing os module

size = os.path.getsize("filename")

print("Size of the file is", size," bytes.")

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

Traceback (most recent call last):


File "C:\Users\GFG\Desktop\GeeksForGeeksOSFile.py", line
6, in
os.close(file)
TypeError: an integer is required (got type _io.TextIOWrapper)

os.popen(): This method opens a pipe to or from command.


The return value can be read or written depending on whether
the mode is ‘r’ or ‘w’.
Example:
import os
fd = "GFG.txt"

# popen() is similar to open()


file = open(fd, 'w')
file.write("Hello")
file.close()
file = open(fd, 'r')
text = file.read()
print(text)

# popen() provides a pipe/gateway and accesses the file directly


file = os.popen(fd, 'w')
file.write("Hello")
# File not closed, shown in next function.

Output:
Hello
Note: Output for popen() will not be shown, there would be
Python tutorial

direct changes into the file.

Whole methods of os module:


import os
# Show all os module methods
print(dir(os))

# Show your current directory


print("My current working directory: ", os.getcwd())

# Show all files and folders of current directory


print("Files and Folders of current directory: ", os.listdir())

# Make a new folder in current directory


os.mkdir("My New Folder")

# Make folder in folder in folder....in current directory


os.makedirs("Folder_1/Folder_2/Folder3")

# Rename a file
os.rename("Hariom.txt", "HSR.txt")

# Join paths
print(os.path.join("D:", "/HSR"))

# Return true if path is exist otherwise return false


print("Path Exist: ", os.path.exists("C:/Program Files"))

# Return true if given path is a file otherwise return false


print("IsFile: ", os.path.isfile("C:/Program Files"))

# Return true if given path is a folder otherwise return false


print("IsDirectory: ", os.path.isdir("C:/Program Files"))

# Get environment variable


print("Environment Variable Path: ", os.environ.get('path'))

# Change your current directory


os.chdir("C:")
print("Now my current directory: ", os.getcwd())
print("Files and Folders of current directory: ", os.listdir())

What is string formatting?

String formatting is attractively designing your string using formatting


techniques provided by the particular programming language. We have
different string formatting techniques in Python. We are now going to
Python tutorial

explore the new f-string formatting technique.

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().

Python Random Module


Python Random module is an in-built module of Python which
is used to generate random numbers. These are pseudo-
random numbers means these are not truly random. This
module can be used to perform random actions such as
generating random numbers, print random a value for a list or
string, etc.
There are different types of functions used in a random module which is given below:

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.

Example: Generate a random number


import random
random_number = random.randint(1, 100) # Print a random number between 1 to 100
print("Random number is: ", random_number)

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

Random number is: 69


Floating point random number is: 98.18488071807357
0.020714958796483107

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

# Program for choose a random channel from list


List = ["Aaj tak", "Sony wah", "Sony sab", "news 24", "Star plus", "zee cinema", "Star gold", "Sony
max", "& pictures"]
choice = random.choice(List)
Python tutorial
print("Will you watch", choice, "?")

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]

print("Original list : ")


print(sample_list)

# 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]

After the first shuffle :


[4, 3, 5, 2, 1]

After the second shuffle :


[1, 3, 4, 5, 2]

Randrange():
It returns a random number within the range
Example:
import random

# Using randrange() to generate numbers from 0-99


print ("Random number from 0-100 is : ",end="")
print (random.randrange(100))

# Using randrange() to generate numbers from 50-99


print ("Random number from 50-100 is : ",end="")
print (random.randrange(50,100))

# Using randrange() to generate numbers from 50-99


# skipping 5
print ("Random number from 50-100 skip 5 is : ",end="")
print (random.randrange(50,100,5))
Python tutorial

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

# Prints list of random items of given length


list1 = [1, 2, 3, 4, 5]

print(sample(list1, 3))
Python tutorial

Output:
[2, 3, 5]

The time Module


There is a popular time module available in Python which provides functions for working with times
and for converting between representations.

Get current time:


import time
localtime = time.asctime(time.localtime(time.time()))
print("Your current time is: ", localtime)

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()

print("\nUsing for loop")


for i in range(10):
print("I am Hariom!")

print("Time of for loop is: ", time.time() - initial2, "seconds")

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

Using for loop


I am Hariom!
I am Hariom!
I am Hariom!
I am Hariom!
I am Hariom!
Python tutorial

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

n = int(input("Enter a number: "))


for i in range(1, 11):
time.sleep(2) # It will pause for 2 seconds in every conditions
print(n, " X ", i, " = ", n*i)

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

The datetime Module


The datetime module enables us to create the custom date objects, perform various
operations on dates like the comparison, etc.

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

Get Current Date


Python tutorial

To return the current local date today() function of date class is


used.
Example:
from datetime import date
print(date.today())

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

# date object of today's date


today = date.today()

print("Current year:", today.year)


print("Current month:", today.month)
print("Current day:", today.day)

Output:
Current year: 2022
Current month: 2
Current day: 9

Strftime() method:
Python tutorial

It takes one parameter, format, to specify the format of the


returned string.
Month name, short version Dec
%b
%B Month name, full version December
%m Month as a number 01-12 12
%y Year, short version, without 18
century
%Y Year, full version 2018
%H Hour 00-23 17
%I Hour 00-12 05
%p AM/PM PM
%M Minute 00 – 59 41
Example:
import datetime
current = datetime.datetime.now()
year = current.strftime("%Y")
print("Current Month name short version: ", current.strftime("%b"))
print("Current Month name full version: ", current.strftime("%B"))
print("Current Month as a number: ", current.strftime("%m"))
print("Current Year name short version: ", current.strftime("%y"))
print("Current Year name full version: ", current.strftime("%Y"))
print("Current Hour [in 24 hour format]: ", current.strftime("%H"))
print("Current Hour [in 12 hour format]: ", current.strftime("%I"))
print("Current Minutes: ", current.strftime("%M"))
print("AM or PM: ", current.strftime("%p"))

Output:
Current Month name short version: Feb
Current Month name full version: February
Current Month as a number: 02
Python tutorial

Current Year name short version: 22


Current Year name full version: 2022
Current Hour [in 24 hour format]: 14
Current Hour [in 12 hour format]: 02
Current Minutes: 30
AM or PM: PM

The calendar module


Python provides a calendar object that contains various methods to work with the
calendars.

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

Printing the calendar of whole year


The prcal() method of calendar module is used to print the calendar of the entire year.
The year of which the calendar is to be printed must be passed into this method.
Python tutorial

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

Python based project. It is generally good to have one new


virtual environment for every Python based project you work on.
So the dependencies of every project are isolated from the
system and each other.
How does a virtual environment work?
We use a module named virtualenv which is a tool to create
isolated Python environments. virtualenv creates a folder which
contains all the necessary executables to use the packages that
a Python project would need.
Installing virtualenv
$ pip install virtualenv
Test your installation:
$ virtualenv --version
Using virtualenv
You can create a virtualenv using the following command:
$ virtualenv my_name
After running this command, a directory named my_name will be
created. This is the directory which contains all the necessary
executables to use the packages that a Python project would
need. This is where Python packages will be installed.
Now after creating virtual environment, you need to activate it.
Remember to activate the relevant virtual environment every
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

Python enumerate() Function


Python enumerate() function returns an enumerated object. It takes two parameters first
is a sequence of elements and the second is the start index of the sequence. We can get
sequence elements either through a loop or next() method.

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:

[(0, 1), (1, 2), (2, 3)]

Python enumerate() Function using loop:


Example 1:
1. result = enumerate([1,2,3])
2. # Displaying result
3. for element in result:
4. print(element)

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.

1. # Python enumerate() function example


Python tutorial
2. # Calling function
3. result = enumerate([1,2,3],10)
4. # Displaying result
5. for element in result:
6. print(element)

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)

# getting desired output from tuple


for count, ele in enumerate(l1):
print(count)
print(ele)

Output:
(0, 'eat')
(1, 'sleep')
(2, 'repeat')

100 eat
101 sleep
102 repeat
Python tutorial

0
eat
1
sleep
2
repeat

How Import Works In Python?


How does the import keyword work?

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

There are two methods to use functions or variables after importing:

 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:

from flask import Flask

We can also choose to rename an imported resource, like this:


import pandas as pd

This renames the imported resource pandas to pd.


We can not access it using pandas keyword; instead, we have to use pd or the compiler
will show an error. This case comes in handy when the module name is difficult or
lengthy, and we have to use a module again and again to call its functions.
Note: import module as module_name does not rename the module originally
but only for a specific program where it is imported using this sort of keyword.

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.

If __name__==__main__ usage & necessity


What is __name__?
“A __name__ is a built-in variable that returns us the name
Python tutorial

of the module being used.”


In simple words, by using __name__, we can check whether our
module is being imported or run directly.
If we run it in the same module that it is created in, then it will
print “main” onto the screen; otherwise, if it is being used
elsewhere, then it will print the name of its module or file it is
created in.
Example:

#tutmain1.py
print("__name__ in tutmain1.py is set to"+__name__)

Output:

__name__ in tutmain1.py is set to __main__

Let us create a new file tutmain2.py in the same directory


as tutmain1.py
In this new file, let us import tutmain1.py so that we can
examine the __name__ variable in tutmain2.py and let us also
print the __name__ variable in tutmain2.py
Example:

#tutmain2.py
import tutmain1
Python tutorial

print("__name in tutmain2.py is set to"+__name__)

Output:

__name__ in tutmain2.py is set to tutmain1

Main function in python:


The main is a point of the program from where the program starts its
execution. Every program has its own main function. The main function can
only be executed when it is being run in the same program. If the file is
being imported, then it is no longer the main function because the file that is
importing it has its own “main” function.

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

What are the Advantages of using if __name__


== “__main__” statement?
Following are the advantages of using if __name__ ==
“__main__” statement:
Python tutorial

 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!"

def add(a, b):


return a + b

print("The name is ", __name__)


if __name__ == '__main__': # This content will not print in other python file if we import this
file in that python program

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

The name is file1


30
So , now you can see that the code of file1 which is present in
main block has not executed in second file.

Python String join() Method


Python String join() method is a string method and returns a
string in which the elements of the sequence have been joined
by the str separator.
Syntax:
string_name.join(iterable)
Example 1: Working of join() method
# Python program to demonstrate the
# use of join function to join list
# elements with a character.

list1 = ['1','2','3','4']

s = "-"

# joins elements of list1 by '-'


# and stores in sting s
s = s.join(list1)

# join use to join a list of


# strings to a separator s
print(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:

The map() function is a higher-order function. As previously stated, this


function accepts another function and a sequence of ‘iterables’ as parameters
and provides output after applying the function to each iterable in the
sequence. It has the following syntax:

SYNTAX: map(function, iterables)


Python tutorial

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)

cube = list(map(lambda x: x*x*x, lst))


print("Cubes are: ", cube)

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:

SYNTAX: filter (function, iterables)

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

gt_than_10 = list(filter(is_Greater_10, list_1))


print("Numbers greater tha 10: ", gt_than_10)

def is_Loewr_10(num):
return num<10

lw_than_10 = list(filter(is_Loewr_10, list_1))


print("Numbers lower than 10: ", lw_than_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:

The reduce() function applies a provided function to ‘iterables’ and returns a


single value, as the name implies.
Python tutorial

SYNTAX: reduce(function, iterables)

The function specifies which expression should be applied to the ‘iterables’ in


this case. The function tools module must be used to import this 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)

# By using reduce function


total_sum = reduce(lambda x, y: x+y, list1)
print("Total sum of list is: ", total_sum)

total_product = reduce(lambda x, y: x*y, list1)


print("Total product of list is: ", total_product)

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.

Before understanding the Decorator, we need to know some important concepts of


Python.

Python also allows to use decorator in easy way with @symbol.

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()

print("\nThis is another way to use decorator in python")


@dec1
def name_2():
print("I am also HSR")

name_2()

Output:
Executing Now
My name is Hariom Mewada
Executed
Python tutorial

This is another way to use decorator in python


Executing Now
I am also HSR
Executed

Python OOPs Concepts


Like other general-purpose programming languages, Python is
also an object-oriented language since its beginning. It allows us
to develop applications using an Object-Oriented approach.
In Python, we can easily create and use classes and objects.
An object-oriented paradigm is to design the program using
classes and objects. The object is related to real-word entities
such as book, house, pencil, etc. The oops concept focuses on
writing the reusable code. It is a widespread technique to solve
the problem by creating objects.
Major principles of object-oriented programming system are
given below.
o Class
o Object
o Method
o Inheritance
o Polymorphism
Python tutorial
o Data Abstraction
o Encapsulation
Class
The class can be defined as a collection of objects. It is a logical entity that has some
specific attributes and methods. For example: if you have an employee class, then it
should contain an attribute and method, i.e. an email id, name, age, salary, etc.

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.

It provides the re-usability of the code.

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

synonyms because data abstraction is achieved through encapsulation.

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.

Object-oriented vs. Procedure-oriented Programming languages


The difference between object-oriented and procedure-oriented programming is given
below:

Inde Object-oriented Programming Procedural Programming


x

1. Object-oriented programming is the Procedural programming uses a list


problem-solving approach and used of instructions to do computation
where computation is done by using step by step.
objects.

2. It makes the development and In procedural programming, It is


maintenance easier. not easy to maintain the codes
when the project becomes lengthy.

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.

4. It provides data hiding. So it is more Procedural language doesn't


secure than procedural languages. provide any proper way for data
You cannot access private data from binding, so it is less secure.
anywhere.

5. Example of object-oriented Example of procedural languages


programming languages is C++, are: C, Fortran, Pascal, VB etc.
Java, .Net, Python, C#, etc.

Creating classes in Python


In Python, a class can be created by using the keyword class, followed by the class name.
The syntax to create a class is given below.

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.

Creating an instance of the class


A class needs to be instantiated if we want to use the class attributes in another class or
method. A class can be instantiated by calling the class using the class name.

The syntax to create the instance of the class is given below.

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

and attaining the dictionary. All objects in Python have an


attribute __dict__, which is a dictionary object containing all
attributes defined for that object itself. The mapping of
attributes with its values is done to generate a dictionary.

Delete the Object


We can delete the properties of the object or object itself by using the del keyword.
Consider the following example.

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.

Creating function in class:


class Employee:
no_of_Leaves = 10
def Print_Details(self):
return f"Name is {self.name}, salary is {self.salary} and role is {self.role}"
Python tutorial
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(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.

Constructors can be of two types.

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.

Creating the constructor in python


In Python, the method the __init__() simulates the constructor of the class. This method
is called when the class is instantiated. It accepts the self-keyword as a first argument
which allows accessing the attributes or method of the class.

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.

Consider the following example to initialize the Employee class attributes.

Example
class Employee:
def __init__(self, Name, Role, Salary):
self.name = Name
self.role = Role
self.salary = Salary

Hariom = Employee("Hariom", "Software developer", 10000000)


print(f"Name is {Hariom.name}, Role is {Hariom.role} and Salary is {Hariom.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")

Python Parameterized Constructor


The parameterized constructor has multiple parameters along with the self. Consider the
following example.
Python tutorial

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:

This is parametrized constructor


Hello John

Python Default Constructor


When we do not include the constructor in the class or forget to declare it, then that
becomes the default constructor. It does not perform any task but initializes the objects.
Consider the following example.

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

More than One Constructor in Single class


Let's have a look at another scenario, what happen if we declare the two same
constructors in the class.

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:

The Second Constructor

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.

Note: The constructor overloading is not allowed in Python.

Built-in class attributes


Along with the other attributes, a Python class also contains some built-in class attributes
which provide information about the class.

The built-in class attributes are given in the below table.

SN Attribute Description

1 __dict__ It provides the dictionary containing the information about the


class namespace.

2 __doc__ It contains a string which has the class documentation


Python tutorial
3 __name__ It is used to access the class name.

4 __module It is used to access the module in which, this class is defined.


__

5 __bases__ It contains a tuple including all base classes.

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__

Python Class Method Decorator


@classmethod
In Python, the @classmethod decorator is used to declare a method in the class as a
class method that can be called using ClassName.MethodName(). The class method
can also be called using an object of the class.

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 Decorator is a built-in function in Python. It can be applied


to any method of the class. We can change the value of variables using this
method too.

@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.

The following example declares a class method.


class Employee:
no_of_leaves = 12
Working_time = 8
no_of_stocks = 5

@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

Class Methods As Alternative Constructors


class Employee:

def __init__(self, Name, Role, Salary):


self.name = Name
Python tutorial
self.role = Role
self.salary = Salary

@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

Raj = Employee.from_slash("Raj Rajput / Manager / 35000")


Hariom = Employee.from_slash("Hariom Rajput / Instructor / 85000")
print(f"Details of Employee: Name is {Raj.name}, salary is {Raj.salary} and role is {Raj.role}")
print(f"Details of Employee: Name is {Hariom.name}, salary is {Hariom.salary} and role is
{Hariom.role}")

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:

text = "Python tutorial for absolute beginners."


Python tutorial

t = text.split()
print(t)

Here, we are not providing it any separator as a parameter, so


it will automatically divide, taking whitespace as a separator.
The output will be a list, such as:
['Python', 'tutorial', 'for', 'absolute', 'beginners.']

Static Method using @staticmethod


Decorator
The @staticmethod is a built-in decorator that defines a static method in the
class in Python. A static method doesn't receive any reference argument
whether it is called by an instance of a class or by the class itself.

@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:

Class method Static Method


Taking a class or, in short,There is no such restriction
Python tutorial

of any specific parameter


form cls as an argument is
related to class in the Static
a must for a class method.
method.
With the help of class
With a static method, we
methods, we can change
can not change or alter the
and alter the variables of
class state.
the class.
Class methods are
restricted to OOPs, so we The static method is not
can only use them if a restricted to a class.
class exists.
We generally use class
methods to create factory
methods. Factory methods Static methods are used to
return a class object which create utility functions.
is similar to a constructor
for different use cases.

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

Python Multiple inheritance


Python provides us the flexibility to inherit multiple base classes in the child class.

The syntax to perform multiple inheritance is given below.

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}"

class Player: # Class 2


def __init__(self, Game, position):
self.game = Game
self.position = position

def Print_details(self):
return f"Student game is {self.game} and Position is {self.position}"

class Cool_Student(Student, Player): # Inherit all properties of class 1 and class 2


def language(self):
language = "Python"
return f"Language : {language}"
Python tutorial
hariom = Cool_Student("hariom", "12th", 1005, 90)
print(hariom.Print_details())
hariom.game = "Cricket"
hariom.position = "State Champian"
print(hariom.game)
print(hariom.position)
print(hariom.language())

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

The syntax of multi-level inheritance is given below.

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

The issubclass(sub,sup) method


The issubclass(sub, sup) method is used to check the relationships between the specified
classes. It returns true if the first class is the subclass of the second class, and false
otherwise.

Consider the following example.

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

The isinstance (obj, class) method


The isinstance() method is used to check the relationship between the objects and
classes. It returns true if the first parameter, i.e., obj is the instance of the second
parameter, i.e., class.

Consider the following example.

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.

Consider the following example to perform method overriding in python.

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

Access Modifiers in Python : Public, Private


and Protected
Various object-oriented languages like C++, Java, Python
control access modifications which are used to restrict
access to the variables and methods of the class. Most
programming languages has three forms of access
modifiers, which are Public, Protected and Private in a
class.
Python uses ‘_’ symbol to determine the access control for
a specific data member or a member function of a class.
Access specifiers in Python have an important role to play
in securing data from unauthorized access and in
preventing it from being exploited.
A Class in Python has three types of access modifiers:
 Public Access Modifier
 Protected Access Modifier
 Private Access Modifier

Public Access Modifier:


The members of a class that are declared public are easily
accessible from any part of the program. All data members
and member functions of a class are public by default.
Example:
# program to illustrate public access modifier in a class
Python tutorial
class First:

# constructor
def __init__(self, name, age):
# public data members
self.Name = name
self.Age = age

# public member function


def displayAge(self):
# accessing public data member
print("Age: ", self.Age)

# creating object of the class


obj = First("R2J", 20)

# accessing public data member


print("Name: ", obj.Name)

# calling public member function of the class


obj.displayAge()

Output:
Name: R2J
Age: 20

Protected Access Modifier:


The members of a class that are declared protected are
only accessible to a class derived from it. Data members of
a class are declared protected by adding a single
underscore ‘_’ symbol before the data member of that
class.
Example:
# program to illustrate protected access modifier in a class

# 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

# protected member function


def _displayRollAndBranch(self):
# accessing protected data members
print("Roll: ", self._roll)
print("Branch: ", self._branch)

# derived class
class Juniar(Student):

# constructor
def __init__(self, name, roll, branch):
Student.__init__(self, name, roll, branch)

# public member function


def displayDetails(self):
# accessing protected data members of super class
print("Name: ", self._name)

# accessing protected member functions of super class


self._displayRollAndBranch()

# creating objects of the derived class


obj = Juniar("R2J", 1706256, "Information Technology")

# calling public member functions of the class


obj.displayDetails()
print(obj._My_Self)

Output:
Name: R2J
Roll: 1706256
Branch: Information Technology
Hariom Singh Rajput

Private Access Modifier:


The members of a class that are declared private are
accessible within the class only, private access modifier is
the most secure access modifier. Data members of a class
Python tutorial

are declared private by adding a double underscore ‘__’


symbol before the data member of that class.
Example:
# program to illustrate private access modifier in a class

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

# private member function


def __displayDetails(self):
# accessing private data members
print("Name: ", self.__name)
print("Roll: ", self.__roll)
print("Branch: ", self.__branch)

# public member function


def accessPrivateFunction(self):
# accessing private member function
self.__displayDetails()

# creating object

obj = Geek("R2J", 1706256, "Information Technology")

# calling public member function of the class


obj.accessPrivateFunction()

# 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 in Python


In this tutorial, we are going to discuss the name mangling process in Python and how we
can use the name mangling process in Python with different methods.

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)

# There is no need to use name mangling because it is a Protected specifier


print("Course: ", Student._Course)

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

# Creating a base class


class Base:
def __init__(self):

# Protected member
self._a = 2

# Creating a derived class


class Derived(Base):
def __init__(self):

# Calling constructor of
# Base class
Base.__init__(self)
print("Calling protected member of base class: ",
self._a)

# Modify the protected variable:


self._a = 3
print("Calling modified protected member outside class: ",
self._a)
Python tutorial

obj1 = Derived()

obj2 = Base()

# Calling protected member


# Can be accessed but should not be done due to convention
print("Accessing protedted member of obj1: ", obj1._a)

# Accessing the protected variable outside


print("Accessing protedted member of obj2: ", obj2._a)

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"

# Creating a derived class


class Derived(Base):
def __init__(self):

# 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)

# Uncommenting print(obj1.c) will


# raise an AttributeError

# Uncommenting obj2 = Derived() will


# also raise an AtrributeError as
# private member of base class
# is called inside derived class

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'

Traceback (most recent call last):


File "/home/4d97a4efe3ea68e55f48f1e7c7ed39cf.py", line 27,
in <module>
obj2 = Derived()
File "/home/4d97a4efe3ea68e55f48f1e7c7ed39cf.py", line 20,
in __init__
print(self.__c)
AttributeError: 'Derived' object has no attribute '_Derived__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.

That is exactly the abstraction that works in the object-oriented concept.

“An abstract class is a class that holds an abstract method.”


Python tutorial

And

“An abstract method is a method defined inside an abstract class.”

Why Abstraction is Important?


In Python, an abstraction is used to hide the irrelevant data/class in order to reduce the
complexity. It also enhances the application efficiency.

Abstraction classes in Python


In Python, abstraction can be achieved by using abstract classes and interfaces.

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. from abc import ABC


2. class ClassName(ABC):

We import the ABC class from the abc module.

Abstract Base Classes


An abstract base class is the common application program of the interface for a set of
subclasses. It can be used by the third-party, which will provide the implementations
such as with plugins. It is also beneficial when we work with the large code-base hard to
remember all the classes.

Working of the Abstract Classes


Unlike the other high-level language, Python doesn't provide the abstract class itself. We
need to import the abc module, which provides the base for defining Abstract Base
classes (ABC). The ABC works by decorating methods of the base class as abstract. It
registers concrete classes as the implementation of the abstract base. We use
Python tutorial

the @abstractmethod decorator to define an abstract method or if we don't provide the


definition to the method, it automatically becomes the abstract method. Let's understand
the following example.

Following is the syntax for defining an abstract method in an abstract class in


Python:

from abc import ABC, abstractmethod


Class MyClass(ABC):
@abstractmethod
def mymethod(self):
#empty body
pass

Important points about abstract class in Python:

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:

from abc import ABC, abstractmethod

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:

# Python program demonstrate


# abstract base class work
from abc import ABC, abstractmethod
class Car(ABC):
@abstractmethod
def mileage(self): # Force for making mileage function in all child classes
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):
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:

The mileage is 30kmph


The mileage is 27kmph
The mileage is 25kmph
The mileage is 24kmph

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.

Example of inbuilt polymorphic functions :


# Python program to demonstrate in-built poly-
# morphic functions

# len() being used for a string


print(len("geeks"))

# len() being used for a list


print(len([10, 20, 30]))

Output:
5
3
Python tutorial

Examples of user-defined polymorphic functions :


# A simple Python function to demonstrate
# Polymorphism

def add(x, y, z = 0):


return x + y+z

# 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.

Method Overriding in classes:


Method overriding is an ability of any object-oriented
programming language that allows a subclass or child class to
provide a specific implementation of a method that is already
provided by one of its super-classes or parent classes. When a
method in a subclass has the same name, same parameters or
signature and same return type(or sub-type) as a method in its
super-class, then the method in the subclass is said
to override the method in the super-class.
Example :
class A:
classVar1 = "I am a variable of class A" # Third Find here

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

def __init__(self): # Override the constructor


# self.classVar1 = "I am a variable of class B inside The Constructor" # First Find here
pass

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

def __init__(self): # Override the constructor


super().__init__()
self.classVar1 = "I am a variable of class B inside The Constructor" # First Find here

a = A()
b = B()
print(b.classVar1)

Output:
Python tutorial

I am a variable of class B inside The Constructor


Example 2: Use super after 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

def __init__(self): # Override the constructor


self.classVar1 = "I am a variable of class B inside The Constructor" # First Find here
super().__init__()

a = A()
b = B()
print(b.classVar1)

Output:
I am a variable of class A inside The Constructor

Dunder or magic methods in Python


Dunder or magic methods in Python are the methods having two
prefix and suffix underscores in the method name. Dunder here
means “Double Under (Underscores)”. These are commonly
used for operator overloading. Few examples for magic
methods are: __init__, __add__, __len__, __repr__ etc.
Here’s a simple implementation :
# declare our own string class
class String:

# magic method to initiate object


Python tutorial
def __init__(self, string):
self.string = string

# Driver Code
if __name__ == '__main__':

# object creation
string1 = String('Hello')

# print object location


print(string1)

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:

# magic method to initiate object


def __init__(self, string):
self.string = string

# print our string object


def __repr__(self):
return 'Object: {}'.format(self.string)

# Driver Code
if __name__ == '__main__':

# object creation
string1 = String('Hello')

# print object location


print(string1)
Python tutorial

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}"

Other magic/dunder methods in python:

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 __add__(self, other): # Dunder method


return self.salary + other.salary

def __truediv__(self, other):


return self.salary / other.salary

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)

emp1 = Employee("Hariom", "Programmer", 100000)


emp2 = Employee("Abhishek", "Manager", 500000)

print(emp1+emp2)
print(emp1/emp2)
Python tutorial
print(emp1)
print(repr(emp1))
print(len(emp2))

Output:

600000

0.2

Name is Hariom, salary is 100000 and role is Programmer

Employee('Hariom', 'Programmer', 100000)

MAPPING OPERATORS TO FUNCTIONS

This table shows how abstract operations correspond to operator symbols in the Python syntax and
the functions in the operator module.

Operation Syntax Function

Addition a + b add(a, b)

Concatenation seq1 + seq2 concat(seq1, seq2)

Containment Test o in seq contains(seq, o)

Division a / b div(a, b) # without __future__.division

Division a / b truediv(a, b) # with __future__.division

Division a // b floordiv(a, b)

Bitwise And a & b and_(a, b)

Bitwise Exclusive Or a ^ b xor(a, b)

Bitwise Inversion ~ a invert(a)

Bitwise Or a | b or_(a, b)
Python tutorial
Exponentiation a ** b pow(a, b)

Identity a is b is_(a, b)

Identity a is not b is_not(a, b)

Indexed Assignment o[k] = v setitem(o, k, v)

Indexed Deletion del o[k] delitem(o, k)

Indexing o[k] getitem(o, k)

Left Shift a << b lshift(a, b)

Modulo a % b mod(a, b)

Multiplication a * b mul(a, b)

Negation (Arithmetic) - a neg(a)

Negation (Logical) not a not_(a)

Right Shift a >> b rshift(a, b)

Sequence Repitition seq * i repeat(seq, i)

Slice Assignment seq[i:j] = values setslice(seq, i, j, values)

Slice Deletion del seq[i:j] delslice(seq, i, j)

Slicing seq[i:j] getslice(seq, i, j)

String Formatting s % o mod(s, o)

Subtraction a - b sub(a, b)

Truth Test o truth(o)

Ordering a < b lt(a, b)

Ordering a <= b le(a, b)


Python tutorial
Equality a == b eq(a, b)

Difference a != b ne(a, b)

Ordering a >= b ge(a, b)

Ordering a > b gt(a, b)

Python @property decorator


@property decorator is a built-in decorator in Python which is
helpful in defining the properties effortlessly without manually
calling the inbuilt function property(). Which is used to return the
property attributes of a class from the stated getter, setter and
deleter as parameters.
Theoretically speaking, Python property decorator is composed of four
things, i.e., getter, setter, deleted, and Doc. The first three are methods, and
the fourth one is a docstring or comment.

Syntax:

@property
#def getter method

Use @property along with the getter method to access the


value of the attribute.
A property decorator is used for setting the parameters. In OOP,
the setter is an important part of the program as we can easily
get the values passed in parameters. Without a setter, it is
impossible to update the values passed as parameters during
object creation. Setters are usually used in Oop to set the value
Python tutorial

of private attributes in a class.


Syntax:

@function_name.setter
#def function

@function_name.setter is a setter method with which we


can set the value of the attribute
Deleter is used to delete the values passed as a parameter
before. We can use a setter if we want to update or change the
value, but we can not use it to delete the value. This is where
deleter comes in; it removes the previous value and sets the
variable equal to none. As in OOP, we do not completely erase
the existence of some variable but sets it equal to none.
Syntax:

# Deleter method
@function_name.deleter

@function_name.deleter is a deleter method which can


delete the assigned value by the setter method
Advantages of @property in Python:
Following are some advantages of using @property in Python:
 The syntax of defining @property is very concise and
readable.
Python tutorial
 We can access instance attributes while using the getters
and setter to validate new values. This will avoid accessing
or modifying the data directly.
 By using @property, we can reuse the name of a property.
This will prevent us from creating new names for the
getters, setters, and deleters.
Example:
class Employee:
def __init__(self, fname, lname):
self.fname = fname
self.lname = lname

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

emp1 = Employee("Hariom", "mewada")

print("My first name : ", emp1.fname)


print("My last name : ", emp1.lname)
print("My old Email is: ", emp1.Email)
emp1.lname = "Rajput"
print("My new Email is: ", emp1.Email)

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

Your Email has been deleted successfully!


Your Email is not set. Please set it using setter...

Code introspection in Python


Introspection is an ability to determine the type of an object at
runtime. Everything in python is an object. Every object in
Python may have attributes and methods. By using
introspection, we can dynamically examine python objects.
Code Introspection is used for examining the classes, methods,
Python tutorial

objects, modules, keywords and get information about them so


that we can utilize it. Introspection reveals useful information
about your program’s objects. Python, being a dynamic, object-
oriented programming language, provides tremendous
introspection support. Python’s support for introspection runs
deep and wide throughout the language.
Python provides some built-in functions that are used for code
introspection.They are:
1.type() : This function returns the type of an object.
2.dir() :This function return list of methods and attributes
associated with that object.
3.str() :This function converts everything into a string .
4.id() :This function returns a special id of an object.
Example:
class Employee:
def __init__(self, fname, lname):
self.fname = fname
self.lname = lname

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

emp1 = Employee("Hariom", "mewada")

# 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

Object Introspection using str method:


After Typecasting type of a is: <class 'str'>
After Typecasting type of b is: <class 'str'>

Object Introspection using id method:


Id of given string is: 1629703928560
Id of given string is: 1629703928752
Id of a is: 1629703983024

Object Introspection using dir method:


Information about given string is: ['__add__', '__class__',
'__contains__', '__delattr__', '__dir__', '__doc__', '__eq__',
'__format__', '__ge__', '__getattribute__', '__getitem__',
'__getnewargs__', '__gt__', '__hash__', '__init__',
'__init_subclass__', '__iter__', '__le__', '__len__', '__lt__',
'__mod__', '__mul__', '__ne__', '__new__', '__reduce__',
'__reduce_ex__', '__repr__', '__rmod__', '__rmul__',
'__setattr__', '__sizeof__', '__str__', '__subclasshook__',
'capitalize', 'casefold', 'center', 'count', 'encode', 'endswith',
'expandtabs', 'find', 'format', 'format_map', 'index', 'isalnum',
'isalpha', 'isascii', 'isdecimal', 'isdigit', 'isidentifier', 'islower',
'isnumeric', 'isprintable', 'isspace', 'istitle', 'isupper', 'join', 'ljust',
'lower', 'lstrip', 'maketrans', 'partition', 'removeprefix',
Python tutorial

'removesuffix', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit',


'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title',
'translate', 'upper', 'zfill']
Information about given object is: ['Email', 'Explain', '__class__',
'__delattr__', '__dict__', '__dir__', '__doc__', '__eq__',
'__format__', '__ge__', '__getattribute__', '__gt__', '__hash__',
'__init__', '__init_subclass__', '__le__', '__lt__', '__module__',
'__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__',
'__setattr__', '__sizeof__', '__str__', '__subclasshook__',
'__weakref__', 'fname', 'lname']

Inspect Module in Python


The inspect module helps in checking the objects present in the
code that we have written. As Python is an OOP language and
all the code that is written is basically an interaction between
these objects, hence the inspect module becomes very useful in
inspecting certain modules or certain objects. We can also use it
to get a detailed analysis of certain function calls or tracebacks
so that debugging can be easier.
The inspect module provides a lot of methods, these methods
can be classified into two categories i.e. methods to verify the
type of token and methods to retrieve the source of token.
Methods to verify the type of token:
 isclass(): The isclass() method returns True if that object is
a class or false otherwise. When it is combined with
Python tutorial

the getmembers() functions it shows the class and its type.


It is used to inspect live classes.

 ismodule(): This returns true if the given argument is an


imported module.

 isfunction(): This method returns true if the given argument


is an inbuilt function name.

 ismethod(): This method is used to check if the argument


passed is the name of a method or not.

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

Methods to retrieve the source of token:


 getclasstree(): The getclasstree() method will help in
getting and inspecting class hierarchy. It returns a tuple of
that class and that of its preceding base classes. That
combined with the getmro() method which returns the base
classes helps in understanding the class hierarchy.

 getmembers(): This method returns the member functions


present in the module passed as an argument of this
method.

 getsource(): This method returns the source code of a


module, class, method, or a function passes as an
argument of getsource() method.
Python tutorial

 getmodule(): This method returns the module name of a


particular object pass as an argument in this method.

 getdoc(): The getdoc() method returns the documentation


of the argument in this method as a string.

Example:
import inspect
import collections
from tkinter import *

class A:
pass

class B(A):
pass

class C(B):
pass

def func(a, b):


return a * b

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

The getclasstree() method of inspect module:


[(<class 'object'>, ()), [(<class '__main__.A'>, (<class
'object'>,)), [(<class '__main__.B'>, (<class '__main__.A'>,)),
[(<class '__main__.C'>, (<class '__main__.B'>,))]]]]

The getmembers() method of inspect module:


[('__class__', <class '__main__.A'>), ('__delattr__', <method-
wrapper '__delattr__' of A object at 0x0000029802BC7FD0>),
('__dict__', {}), ('__dir__', <built-in method __dir__ of A object at
0x0000029802BC7FD0>), ('__doc__', None), ('__eq__',
<method-wrapper '__eq__' of A object at
0x0000029802BC7FD0>), ('__format__', <built-in method
__format__ of A object at 0x0000029802BC7FD0>), ('__ge__',
<method-wrapper '__ge__' of A object at
0x0000029802BC7FD0>), ('__getattribute__', <method-wrapper
'__getattribute__' of A object at 0x0000029802BC7FD0>),
('__gt__', <method-wrapper '__gt__' of A object at
0x0000029802BC7FD0>), ('__hash__', <method-wrapper
'__hash__' of A object at 0x0000029802BC7FD0>), ('__init__',
<method-wrapper '__init__' of A object at
0x0000029802BC7FD0>), ('__init_subclass__', <built-in method
__init_subclass__ of type object at 0x0000029802F757B0>),
('__le__', <method-wrapper '__le__' of A object at
0x0000029802BC7FD0>), ('__lt__', <method-wrapper '__lt__' of
A object at 0x0000029802BC7FD0>), ('__module__',
Python tutorial

'__main__'), ('__ne__', <method-wrapper '__ne__' of A object at


0x0000029802BC7FD0>), ('__new__', <built-in method
__new__ of type object at 0x00007FFBF9CBB780>),
('__reduce__', <built-in method __reduce__ of A object at
0x0000029802BC7FD0>), ('__reduce_ex__', <built-in method
__reduce_ex__ of A object at 0x0000029802BC7FD0>),
('__repr__', <method-wrapper '__repr__' of A object at
0x0000029802BC7FD0>), ('__setattr__', <method-wrapper
'__setattr__' of A object at 0x0000029802BC7FD0>),
('__sizeof__', <built-in method __sizeof__ of A object at
0x0000029802BC7FD0>), ('__str__', <method-wrapper '__str__'
of A object at 0x0000029802BC7FD0>), ('__subclasshook__',
<built-in method __subclasshook__ of type object at
0x0000029802F757B0>), ('__weakref__', None)]

The getsource() method of inspect module:


def func(a, b):
return a * b

The getmodule() method of inspect module:


<module 'collections' from 'C:\\Python310\\lib\\collections\\
__init__.py'>
Python tutorial

The getdoc() method of inspect module:


Toplevel widget of Tk which represents mostly the main window
of an application. It has an associated Tcl interpreter.

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.

There is a lot of complexity in creating iteration in Python; we need to


implement __iter__() and __next__() method to keep track of internal states.

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

There are two terms involved when we discuss generators.


 Generator-Function : A generator-function is defined like a
normal function, but whenever it needs to generate a value,
it does so with the yield keyword rather than return. If the
body of a def contains yield, the function automatically
Python tutorial

becomes a generator function.


Example:
def febonnaci(n):
a = 0
b = 1
for i in range(n):
yield a
a, b = b, a+b

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!")

Output: for febonnaci series


___________Choose any option for continue____________
1. Febonnaci number
2. factorial
1
Enter any number: 25
Python tutorial

The febonnaci sequence is as below:


0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584
4181 6765 10946 17711 28657 46368

Output: for factorial


___________Choose any option for continue____________
1. Febonnaci number
2. factorial
2
Enter any number: 25
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
Factorial of 8 is : 40320
Python tutorial

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

method on the generator object or using the generator object in


a “for in” loop.
Example 1:
# A generator function
def simpleGeneratorFun():
yield 1
yield 2
yield 3

# x is a generator object
x = simpleGeneratorFun()

# Iterating over the generator object using next


print(x.next())
print(x.next())
print(x.next())

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

Difference between Generator function and Normal function


Here is how a generator function differs from a normal function.
 Normal function contains only one return statement whereas generator function
can contain one or more yield statement.
 When called, it returns an object (iterator) but does not start execution immediately.

 Methods like __iter__() and __next__() are implemented automatically. So we can


iterate through the items using next() .

 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.

 Finally, when the function terminates, StopIteration is raised automatically on


Python tutorial

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:

Memory in Bytes: 4508


Memory in Bytes: 56

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.

3. Generate Infinite Sequence

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))

l2 = [i**2 for i in range(1, 11)]


print("\n", l2)
print(type(l2))

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'>

[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]


<class 'list'>
Example 2: List comprehension with condition:
l = [a for a in range(1, 101) if a%5 == 0]
print(l)

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)

# Create a dictionary by using dictionary comprehension with condition


Dict2 = {j : f"My_Item {j} " for j in range(1, 51) if j % 10 == 0}
print(Dict2)

# Interchange key with values


Dict3 = {value : key for key, value in Dict2.items()}
print(Dict3)
Python tutorial

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']

dict_using_comp = {key: value for (key, value) in zip(state, capital)}

print("Output Dictionary using dictionary comprehensions:",


dict_using_comp)
print(type(dict_using_comp))

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))

elif choice == 'B':


Dict1 = {a : f" Item{a} " for a in List}
print(Dict1)
print(type(Dict1))

elif choice == 'C':


Set1 = {a for a in List}
print(Set1)
print(type(Set1))

elif choice == 'D':


Generator1 = (a for a in List)
print(Generator1)
print(type(Generator1))
else:
print("Invalid Input!")

Output:
How many elements you want to add: 10
Enter elements separated by space: Red Blue Green Yellow
Red Purple White Red Yellow Orange

Which type of Comprehension you want to create?


A. For List Comprehension
Python tutorial

B. For Dictionary Comprehension


C. For Set Comprehension
D. For Generator Comprehension

-->
C
{'Orange', 'Purple', 'Green', 'Blue', 'Yellow', 'Red', 'White'}
<class 'set'>

Python Functools – lru_cache()


lru_cache()
lru_cache() is one such function in functools module which
helps in reducing the execution time of the function by using
memoization technique.
Example 1:
import time
from functools import lru_cache

@ 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)

print("Done! Calling again..")


Starting_time2 = time.time()
Some_Work(4)
ending_time2 = time.time()
print("Time taken in execution --> ", ending_time2 - Starting_time2)

print("Called again! ")

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

# Function that computes Fibonacci


# numbers without lru_cache
def fib_without_cache(n):
if n < 2:
return n
return fib_without_cache(n - 1) + fib_without_cache(n - 2)

# Execution start time


begin = time.time()
fib_without_cache(35)

# Execution end time


end = time.time()

print("Time taken to execute the function without lru_cache is", end - begin)

# Function that computes Fibonacci


# numbers with lru_cache
@lru_cache(maxsize=5)
def fib_with_cache(n):
if n < 2:
return n
return fib_with_cache(n - 1) + fib_with_cache(n - 2)

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")

while True: # On next call search will start from here


text = (yield)
if text in book:
print("This text is available in the book!")
else:
print("This text is not available in the book!")

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)

with open("latter.txt", "r") as f:


names = f.read()

while True: # On next call search will start from here


Name = (yield)
if Name in names:
print(f"This Name is available in the latter!")
else:
print("This text is not available in the latter!")

if __name__ == '__main__':

search = searcher()
next(search)
i = input("Enter name: ")
search.send(i)
input("Press any key: ")

i = input("Enter name: ")


search.send(i)
input("Press any key: ")

i = input("Enter name: ")


search.send(i)

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

This Name is available in the latter!

User define module in python:


We can also make our own module in python and import them
into other python files.
Which module we create in python is also end with .py
extension.
Note: The name of module should not start with a number
otherwise this can’t be import.
Example:
Create a module and save it with any name: suppose
‘Module1.py’
# This is a user define module which name is Module1.py
def add(*args):
sum = 0
for i in args:
sum = sum + i
return sum

def diff(a, b):


return a - b

def product(*args):
prd = 1
for i in args:
prd = prd * i
return prd

def div(a, b):


return a / b

Now, create a new python file and import this module.


import Module1

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

If we want to directly use all functions of Module1 than we can


import this module in another way:
from Module1 import *

print("Addition = ", add(3, 4, 6, 10, 2))


print("Subtraction = ", diff(37, 9))
print("Multiplication = ", product(30, 4, 6, 10, 2))
print("Division = ", div(30, 15))

Note: * will import all functions, classes , objects and methods of


any module so that we can use all of these directly.
Output:
Addition = 25
Subtraction = 28
Multiplication = 14400
Python tutorial

Division = 2.0

Create and access a Python package:


Packages are a way of structuring many packages and modules
which helps in a well-organized hierarchy of data set, making
the directories and modules easy to access. Just like there are
different drives and folders in an OS to help us store files,
similarly packages help us in storing other sub-packages and
modules, so that it can be used by the user when necessary.
Creating and Exploring Packages
To tell Python that a particular directory is a package, we create
a file named __init__.py inside it and then it is considered as a
package and we may create other modules and sub-packages
within it. This __init__.py file can be left blank or can be coded
with the initialization code for the package.
To create a package in Python, we need to follow these
three simple steps:
1. First, we create a directory and give it a package name,
preferably related to its operation.
2. Then we put the classes and the required functions in it.
3. Finally we create an __init__.py file inside the directory, to
let Python know that the directory is a package.
Example of Creating Package
Python tutorial

Step 1: first we create __init__.py file.


Ex.-
class car:
car_list = ['Audi', 'BMW', 'Nissan']

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)

Step 2: Now create a setup.py file outside this directory and


import setup from setuptools.
Example:
from setuptools import setup
setup(name="Package_Hariom",
version="1.0.3",
description="This is a python package spatially for car show rooms.",
long_description="This package is now available for only Audi, BMW and Nissan cars.",
author="hariom Singh Rajput",
Email="[email protected]",
Python tutorial
packages=["Package_Hariom"],
install_requires=[])

Step 3: Now open terminal in this directory, and type given


commands below:
Command 1:
PS A:\Python Tutorial\Creating_python_packege> python .\
setup.py sdist bdist_wheel
Output:

C:\Python310\lib\distutils\dist.py:274: UserWarning: Unknown


distribution option: 'Email'
warnings.warn(msg)
running sdist
running egg_info
creating Package_Hariom.egg-info
writing Package_Hariom.egg-info\PKG-INFO
writing dependency_links to Package_Hariom.egg-info\
dependency_links.txt
writing top-level names to Package_Hariom.egg-info\
top_level.txt
writing manifest file 'Package_Hariom.egg-info\SOURCES.txt'
Python tutorial

reading manifest file 'Package_Hariom.egg-info\SOURCES.txt'


adding license file 'Licence.txt'
writing manifest file 'Package_Hariom.egg-info\SOURCES.txt'
running check
warning: check: missing required meta-data: url

warning: check: missing meta-data: if 'author' supplied,


'author_email' should be supplied too

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

copying Package_Hariom.egg-info\SOURCES.txt ->


Package_Hariom-1.0.3\Package_Hariom.egg-info
copying Package_Hariom.egg-info\dependency_links.txt ->
Package_Hariom-1.0.3\Package_Hariom.egg-info
copying Package_Hariom.egg-info\top_level.txt ->
Package_Hariom-1.0.3\Package_Hariom.egg-info
Writing Package_Hariom-1.0.3\setup.cfg
creating dist
Creating tar archive
removing 'Package_Hariom-1.0.3' (and everything under it)
running bdist_wheel
running build
running build_py
creating build
creating build\lib
creating build\lib\Package_Hariom
copying Package_Hariom\__init__.py -> build\lib\
Package_Hariom
installing to build\bdist.win-amd64\wheel
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

Mode LastWriteTime Length Name


---- ------------- ------ ----
-a---- 22-Feb-22 01:36 PM 1895 Package_Hariom-
1.0.3-py3-none-any.whl
-a---- 22-Feb-22 01:36 PM 1339 Package_Hariom-
1.0.3.tar.gz
Python tutorial

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

Now your package has been successfully installed in our


computer.

Step 4: Now open PowerShell and run python.


Example:
PS C:\WINDOWS\system32> python
Python 3.10.2 (tags/v3.10.2:a58ebcc, Jan 17 2022, 14:12:15)
[MSC v.1929 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more
information.
>>> import Package_Hariom
Python tutorial

>>> 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.

Python Math Module


Python math module is defined as the most famous mathematical functions, which includes
trigonometric functions, representation functions, logarithmic functions, etc.

Constants provided by the math module


Math module provides various the value of
various constants like pi, tau. Having such constants saves the
time of writing the value of each constant every time we want to
use it and that too with great precision. Constants provided by
the math module are –
 Euler’s Number
 Pi
 Tau
 Infinity
 Not a Number (NaN)

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

# Print the value of Euler e


print (math.e)

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

# Print the value of pi


print (math.pi)

Output:
3.141592653589793
Tau
Tau is defined as the ratio of the circumference to the radius of
Python tutorial

a circle. The math.tau constant returns the value tau:


6.283185307179586.
Syntax:
math.tau
Example:
# Import math Library
import math

# Print the value of tau


print (math.tau)

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

# Print the positive infinity


print (math.inf)
Python tutorial

# Print the negative infinity


print (-math.inf)

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

# Print the value of nan


print (math.nan)

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

# returning the ceil of 2.3


print ("The ceil of 2.3 is : ", end="")
print (math.ceil(a))

# returning the floor of 2.3


print ("The floor of 2.3 is : ", end="")
print (math.floor(a))

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

# returning the factorial of 5


print("The factorial of 5 is : ", end="")
print(math.factorial(a))

Output:
The factorial of 5 is : 120
Python tutorial

Finding the GCD


gcd() function is used to find the greatest common divisor of two
numbers passed as the arguments.
Example:
import math

a = 15
b = 5

# returning the gcd of 15 and 5


print ("The gcd of 5 and 15 is : ", end="")
print (math.gcd(b, a))

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

# returning the absolute value.


print ("The absolute value of -10 is : ", end="")
print (math.fabs(a))

Output:
The absolute value of -10 is : 10.0
Python tutorial

Finding the Square root


sqrt() function returns the square root of the number.
Example:
import math

# print the square root of 0


print(math.sqrt(0))

# print the square root of 4


print(math.sqrt(4))

# print the square root of 3.5


print(math.sqrt(3.5))

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

Logarithmic and Power Functions


Finding the power of exp
exp() method is used to calculate the power of e i.e. or we
can say exponential of y.
Finding the Logarithm
 log() function returns the logarithmic value of a with base b.
If the base is not mentioned, the computed value is of the
natural log.
 log2(a) function computes value of log a with base 2. This
value is more accurate than the value of the function
discussed above.
 log10(a) function computes value of log a with base 10.
This value is more accurate than the value of the function
discussed above.
Example:
import math

# 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)}")

# returning the log of 2,3


print("The value of log 2 with base 3 is : ", math.log(2, 3))

# returning the log2 of 16


print("The value of log2 of 16 is : ", math.log2(16))

# returning the log10 of 10000


print("The value of log10 of 10000 is : ", math.log10(10000))

Output:
e^3 is: 54.598150033144236, e^-3 is: 0.049787068367863944
Python tutorial

and e^0 is: 1.0


The value of log 2 with base 3 is : 0.6309297535714574
The value of log2 of 16 is : 4.0
The value of log10 of 10000 is : 4.0
Trigonometric and Angular Functions
Finding sine, cosine, and tangent
sin(), cos(), and tan() functions returns the sine, cosine, and
tangent of value passed as the argument. The value passed in
this function should be in radians.
Example:
import math

a = math.pi / 6

# returning the value of sine of pi/6


print("The value of sine of pi/6 is : ", math.sin(a))

# returning the value of cosine of pi/6


print("The value of cosine of pi/6 is : ", math.cos(a))

# returning the value of tangent of pi/6


print("The value of tangent of pi/6 is : ", math.tan(a))

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

 degrees() function is used to convert argument value from


radians to degrees.
 radians() function is used to convert argument value from
degrees to radians.
Example:
import math

a = math.pi / 6
b = 30

# returning the converted value from radians to degrees


print("The converted value from radians to degrees is : ", math.degrees(a))

# returning the converted value from degrees to radians


print("The converted value from degrees to radians is : ", math.radians(b))

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

# returning the value of hypotenuse of 3 and 4


print("The value of hypotenuse of 3 and 4 is : ", math.hypot(a, b))
Python tutorial

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.

isnan() function returns true if the number is “NaN” else returns


false.
Example:
import math
gamma_var = 6
# Printing the gamma value.
print("The gamma value of the given argument is : ", math.gamma(gamma_var))

# checking isinf() values with inbuilt numbers


print(math.isinf(math.pi))
print(math.isinf(math.e))
# checking for inf value
print(math.isinf(float('inf')))

# checking isnan() values with inbuilt numbers


print(math.isnan(math.pi))
print(math.isnan(math.e))
# checking for NaN value
print(math.isnan(float('nan')))

Output:
Python tutorial

The gamma value of the given argument is : 120.0


False
False
True
False
False
True

Python Requests Module - HTTP Request


Introduction
Generally, we look for some information from the website. Or we may want to get access
to social media accounts, checking mails, watching online videos. We likely send the
request using the web browser, and the webserver returns the desired result from the
webserver. To get information from the Internet, we need to send the request through
the web browser.

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.

Python Request Module

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.

o GET - It is used to request data from a server.


o POST - It is used to submit some data to the server for processing it.

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 Request

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.

requests.get(url, param = {key:value}, args)

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.

MAKING A GET REQUESTS


It is quite an easy way to make an HTTP request using the requests module. Following is
the code for making the request.

Here the response object will store the information. Below are the essential properties.

o content - It returns the content of the data for the responses.


o status_code - It returns the status of our request. For example - 200 OK means you made
successful request, 404 NOT FOUND means resource is not found.
o cookies - It uses to obtaining a CookieJar object having all cookies we get from the
server.
Python tutorial

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&#58;&#47;&#47;www&#46;hackerrank&#46;com&#47;do
mains&#47;data&#45;structures&#63;" on this server.<P>\
nReference&#32;&#35;18&#46;8efdd417&#46;1645189469&#4
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>

You don't have permission to access


"http&#58;&#47;&#47;www&#46;hackerrank&#46;com&#47;do
mains&#47;data&#45;structures&#63;" on this server.<P>
Reference&#32;&#35;18&#46;8efdd417&#46;1645189469&#46;
c6f203a
</BODY>
</HTML>

POST Http Method


POST is a request method supported by HTTP used by the
World Wide Web. By design, the POST request method
requests that a web server accepts the data enclosed in the
body of the request message, most likely for storing it. It is often
used when uploading a file or when submitting a completed web
Python tutorial

form.

How to make POST request through Python Requests


Python’s requests module provides in-built method
called post() for making a POST request to a specified URI.
Syntax –
requests.post(url, params={key: value}, args)
Following are the important parameters.

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.

The POST method returns the requests.Response object.

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).

HOW TO CONVERT JSON TO PYTHON DICTIONARY?


We use the r.json() method to create a Python dictionary from the JSON response.

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

Python JSON Module:


JSON stands for JavaScript Object Notation, which is a widely used data format for
data interchange on the web. JSON is the ideal format for organizing data between a
client and a server. Its syntax is similar to the JavaScript programming language. The
main objective of JSON is to transmit the data between the client and the web server. It is
easy to learn and the most effective way to interchange the data. It can be used with
various programming languages such as Python, Perl, Java, etc.

JSON mainly supports 6 types of data type In JavaScript:

o String
o Number
o Boolean
o Null
o Object
o Array

JSON is built on the two structures:

o It stores data in the name/value pairs. It is treated as an object, record, dictionary,


hash table, keyed list.
o The ordered list of values is treated as an array, vector, list, or sequence.

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

easily be deserialized with load()/loads(), which is usually used


to load from string, otherwise, the root object is in list or dict.
See the following table given below.

JSON OBJECT PYTHON OBJECT

object dict

array list

string str

null None

number (int) int

number (real) float

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"
}
]
}

We want to read the content of this file. Below is the


implementation.
import json

# Opening JSON file


f = open('data.json')

# returns JSON object as a dictionary


data = json.load(f)
print(type(data))

# Iterating through the json list


for i in data['Emp_Details']:
print(i)

# Closing file
f.close()

Output:
<class 'dict'>
{'Emp_name': 'Hariom', 'Email':
Python tutorial

'[email protected]', 'Job profile':


'Developer'}
{'Emp_name': 'Abhishek', 'Email': '[email protected]',
'Job profile': 'Intern'}
{'Emp_name': 'Karan', 'Email': '[email protected]',
'Job profile': 'Full time'}

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

Example: This example shows reading from both string and


JSON file. The file shown above is used.
import json

# JSON string
a = '{"name": "Hariom", "languages": "Hindi"}'

# deserializes into dict and returns dict.


y = json.loads(a)
Python tutorial
print("JSON string = ", y)
print()

# JSON file
f = open('data.json', "r")

# Reading from file


data = json.loads(f.read())

# Iterating through the json list


for i in data['Emp_Details']:
print(i)

# Closing file
f.close()

Output:
JSON string = {'name': 'Hariom', 'languages': 'Hindi'}

{'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'}

Convert from Python to JSON


json.dumps() method can convert a Python object into a JSON
string.
Syntax:
json.dumps(dict, indent)
Python tutorial

It takes two parameters:


 dictionary – name of dictionary which should be converted
to JSON object.
 indent – defines the number of units for indentation
Example:
import json

# 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

Python objects and their equivalent conversion to JSON:

Python JSON Equivalent

dict object

list, tuple array


Python tutorial

str string

int, float number

True true

False false

None null

Writing JSON to a file


json.dump() method can be used for writing to JSON file.
Syntax:
json.dump(dict, file_pointer)
It takes 2 parameters:
 dictionary – name of dictionary which should be converted
to JSON object.
 file pointer – pointer of the file opened in write or append
mode.
Example:
import json

# Data to be written
dictionary = {
"Name": "Hariom",
"Roll no.": 56,
"cgpa": 8.6,
"Phone number": "9756770500"
}

with open("sample.json", "w") as f:


Python tutorial
json.dump(dictionary, f)

Output:
{"Name": "Hariom", "Roll no.": 56, "cgpa": 8.6, "Phone number": "9756770500"}

The above program opens a file named sample.json in writing


mode using ‘w’. The file will be created if it does not exist.
Json.dump() will transform dictionary to a JSON string and it will
be saved in the file sample.json.

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"}'

# python object to be appended


y = {"pin": 110096}

# parsing JSON string:


z = json.loads(x)

# appending the data


z.update(y)

# the result is a JSON string:


print(json.dumps(z))

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)

# python object to be appended

y = {"Emp_name": "Nikhil",
"Email": "[email protected]",
"Job profile": "Full Time"
}

write_json(y)

Output: Now data.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"
},
{
"Emp_name": "Nikhil",
"Email": "[email protected]",
"Job profile": "Full Time"
}
]
}

Pickle Module of Python


A developer may sometimes want to send some complex object commands through the
network and save the internal state of their objects to the disk or database for using it
later. To achieve this, the developer can use the serialization process, which is supported
by the standard library, cause of Python's Pickle Module.
Python tutorial

Python pickle module is used for serializing and de-serializing a


Python object structure. Any object in Python can be pickled so
that it can be saved on disk. What pickle does is that it
“serializes” the object first before writing it to file. Pickling is a
way to convert a python object (list, dict, etc.) into a character
stream. The idea is that this character stream contains all the
information necessary to reconstruct the object in another
python script.
The pickle module of python contains the four methods:

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

# Pickling a python object


cars = ['Audi', 'Ferrari', 'BMW', 'Maruti Suzuki', 'Lamborghini', 'Mahindra', 'Tata']
file = "Mycars.pkl"
fileobj = open(file, 'wb') # Note: pickle file will be write only in binary mode
pickle.dump(cars, fileobj)
fileobj.close()
Python tutorial

De-pickling(load) python objects from pickle file:


import pickle
file = "Mycars.pkl"
file_obj = open(file, 'rb')
mycar = pickle.load(file_obj)
print(mycar)
file_obj.close()

Output:
['Audi', 'Ferrari', 'BMW', 'Maruti Suzuki', 'Lamborghini',
'Mahindra', 'Tata']
Pickling(dumps) and de-pickling(loads) without a file:
import pickle

# initializing data to be stored in db


Omkar = {'key': 'Omkar', 'name': 'Omkar Pathak',
'age': 21, 'pay': 40000}
Jagdish = {'key': 'Jagdish', 'name': 'Jagdish Pathak',
'age': 50, 'pay': 50000}

# 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

already serialized, so later references to the same object


won’t be serialized again. (The marshal module breaks for
this.)
2. Object sharing (references to the same object in
different places): This is similar to self- referencing
objects; pickle stores the object once, and ensures that all
other references point to the master copy. Shared objects
remain shared, which can be very important for mutable
objects.
3. User-defined classes and their instances: Marshal does
not support these at all, but pickle can save and restore
class instances transparently. The class definition must be
importable and live in the same module as when the object
was stored.

Regular Expression (re) Module in Python:


A Regular Expressions (RegEx) is a special sequence of
characters that uses a search pattern to find a string or set of
strings. It can detect the presence or absence of a text by
matching with a particular pattern, and also can split a pattern
into one or more sub-patterns. Python provides a re module that
supports the use of regex in Python. Its primary function is to
offer a search, where it takes a regular expression and a string.
Here, it either returns the first match or else none.
Example:
Python tutorial
import re

s = 'GeeksforGeeks: A computer science portal for geeks'

match = re.search(r'portal', s)

print('Start Index:', match.start())


print('End Index:', match.end())

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

Used to drop the special meaning of


\ character following it

[] Represent a character class

^ Matches the beginning

$ Matches the end

Matches any character except


. newline

Means OR (Matches with any of the


| characters separated by it.

? Matches zero or one occurrence

Any number of occurrences


* (including 0 occurrences)

+ One or more occurrences

Indicate the number of occurrences


{} of a preceding regex to match.

() Enclose a group of Regex

Let’s discuss each of these metacharacters in detail


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

 a|b will match any string that contains a or b such as acd,


bcd, abcd, etc.
? – Question Mark
Question mark(?) checks if the string before the question mark
in the regex occurs at least once or not at all. For example –
 ab?c will be matched for the string ac, acb, dabc but will not
be matched for abbc because there are two b. Similarly, it
will not be matched for abdc because b is not followed by c.
* – Star
Star (*) symbol matches zero or more occurrences of the regex
preceding the * symbol. For example –
 ab*c will be matched for the string ac, abc, abbbc, dabc,
etc. but will not be matched for abdc because b is not
followed by c.
+ – Plus
Plus (+) symbol matches one or more occurrences of the regex
preceding the + symbol. For example –
 ab+c will be matched for the string abc, abbc, dabc, but will
not be matched for ac, abdc because there is no b in ac and
b is not followed by c in abdc.
{m, n} – Braces
Braces match any repetitions preceding regex from m to n both
Python tutorial

inclusive. For example –


 a{2, 4} will be matched for the string aaab, baaaac, gaad,
but will not be matched for strings like abc, bc because
there is only one a or no a in both the cases.
(<regex>) – Group
Group symbol is used to group sub-patterns. For example –
 (a|b)cd will match for strings like acd, abcd, gacd, etc.
Special Sequences
Special sequences do not match for the actual character in the
string instead it tells the specific location in the search string
where the match must occur. It makes it easier to write
commonly used patterns.
List of special sequences

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

Matches if the word begins or geeks


ends with the given
character. \b(string) will check
for the beginning of the word \
and (string)\b will check for the bg
\b ending of the word. e get

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

Matches any decimal digit, this 123


is equivalent to the set class
\d [0-9] \d gee1

Matches any non-digit geeks


character, this is equivalent to
\D the set class [^0-9] \D geek1

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

>$

Matches any non- gee<


\W alphanumeric character. \W >

abcda
b

Matches if the string ends with ab\ abab


\Z the given regex Z abab
Example:
import re

# 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

string = """Hello my Number is 1234567898, 9869234560 and


my friend's number is 9876543921 and my teacher's number is 9870543670"""

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"))

# \d+ will match a group on [0-9], group of one or greater size


p = re.compile('\d+')
print(p.findall("I went to him at 11 A.M. on 4th July 1886"))
print()

# \w is equivalent to [a-zA-Z0-9_].
p = re.compile('\w')
print(p.findall("He said * in some_lang."))

# \w+ matches to group of alphanumeric character.


p = re.compile('\w+')
print(p.findall("I went to him at 11 A.M., he said *** in some_language."))

# \W matches to non alphanumeric characters.


p = re.compile('\W')
print(p.findall("he said *** in some_language."))

Output:
['e', 'a', 'd', 'b', 'e', 'a']
Python tutorial

['1', '1', '4', '1', '8', '8', '6']


['11', '4', '1886']

['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

# '\W+' denotes Non-Alphanumeric Characters


# or group of characters Upon finding ','
# or whitespace ' ', the split(), splits the
# string from that point
print(split('\W+', 'Words, words , Words'))
print(split('\W+', "Word's words Words"))

# Here ':', ' ' ,',' are not AlphaNumeric thus,


# the point where splitting occurs
print(split('\W+', 'On 12th Jan 2016, at 11:02 AM'))

# '\d+' denotes Numeric Characters or group of


# characters Splitting occurs at '12', '2016',
Python tutorial
# '11', '02' only
print(split('\d+', 'On 12th Jan 2016, at 11:02 AM'))

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

print(re.sub('ub', '~*', 'Subject has Uber booked already',


flags=re.IGNORECASE))

print(re.sub('ub', '~*', 'Subject has Uber booked already'))

Output:
S~*ject has ~*er booked already
S~*ject has Uber booked already
re.subn()
Python tutorial

subn() is similar to sub() in all ways, except in its way of


providing output. It returns a tuple with count of the total of
replacement and the new string rather than just the string.
Example:
import re

print(re.subn('ub', '~*', 'Subject has Uber booked already'))

t = re.subn('ub', '~*', 'Subject has Uber booked already',


flags=re.IGNORECASE)
print(t)
print(len(t))

# This will give same output as sub() would have


print(t[0])

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

# escape() returns a string with BackSlash '\',


# before every Non-Alphanumeric Character
Python tutorial

# In 1st case only ' ', is not alphanumeric


# In 2nd case, ' ', caret '^', '-', '[]', '\'
# are not alphanumeric
print(re.escape("This is Awesome even 1 AM"))
print(re.escape("I Asked what is this [a-9], he said \t
^WoW"))

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)

res = re.search(r"\D{7} A", s)


print(res.group())

s2 = "My name is hariom"


search = re.search(r"\bhari", s2)

print()
print(search.start())
print(search.end())
print(search.span())

Output:
Python tutorial

<re.Match object; span=(11, 12), match='A'>


re.compile('\\bA')
Welcome to Anandipura!
come to A

11
15
(11, 15)

Python sys Module


The sys module in Python provides various functions and
variables that are used to manipulate different parts of the
Python runtime environment. It allows operating on the
interpreter as it provides access to the variables and functions
that interact strongly with the interpreter. Let’s consider the
below example.
Example:
import sys

print(sys.version)

Output:
3.10.2 (tags/v3.10.2:a58ebcc, Jan 17 2022, 14:12:15) [MSC
Python tutorial

v.1929 64 bit (AMD64)]


Input and Output using sys
The sys modules provide variables for better control over input
or output. We can even redirect the input and output to other
devices. This can be done using three variables –

 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

for line in sys.stdin:


if 'q' == line.rstrip():
break
print(f'Input : {line}')

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

stderr: Whenever an exception occurs in Python it is written to


sys.stderr.
Example:
import sys
Python tutorial
def print_to_stderr(*a):
# Here a is the array holding the objects passed as the argument of the function
print(*a, file=sys.stderr)

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

elif args.o == 'sub':


return args.x - args.y

elif args.o == 'mul':


return args.x * args.y

elif args.o == 'div':


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")

parser.add_argument('--y', type=float, default=0.0,


help="Enter second number. This is a utility for calculation. For more
information please contact on 1001 2002 3003")

parser.add_argument('--o', type=str, default='add',


help="Enter an operation. This is a utility for calculation. For more
information please contact on 1001 2002 3003")
Python tutorial
args = parser.parse_args()
sys.stdout.write(str(calc(args)))

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

Convert Python Script to .exe File


Step 1:
Install the library pyinstaller.
Python tutorial

Type below command in the command prompt.

pip install pyinstaller

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

independent from other files.

Convert .py to .exe with icon:


Step 1: pip install auto-py-to-exe
Step-2: Open directory in cmd where your file is present.\
Step-3: Type auto-py-to-exe
Now a window will be open.
Step-4: fill path of file and icon and set application type (terminal
based or window based) and check other setting according your
need and click on “convert py to exe”.

Convert python code into Android Apk file:


Kivy is a graphical user interface opensource Python library that
allows you to develop multi-platform applications on Windows,
macOS, Android, iOS, Linux, and Raspberry-Pi. In addition to
the regular mouse and keyboard inputs, it also
supports multitouch events. The applications made using Kivy
will similar across all the platforms but it also means that the
applications fell or look will differ from any native application.
Note that it is necessary to have Python 3 on your machine to
make use of the library.
Python tutorial

Installation in Windows:

 Step 1: Update the pip and wheel before installing kivy by


entering this command in cmd-

python -m pip install --upgrade pip wheel setuptools

 Step 2: Install the dependencies-

python -m pip install docutils pygments pypiwin32


kivy.deps.sdl2 kivy.deps.glew
python -m pip install kivy.deps.gstreamer
python -m pip install kivy.deps.angle

 Step 3: Install kivy.


python -m pip install kivy
pip install kivymd

Create an application
Python tutorial

There are three steps of creating an application with kivy:


1. Inherit Kivy’s App class which represents the window for our
widgets
2. Create a build() method, which will show the content of the
widgets.
3. And at last calling of the run() method.
Example:
from kivymd.app import MDApp
from kivymd.uix.label import MDLabel

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 upload your python file on google colab.


Seventh :
!buildozer init

Now go to sample data and open buildozer.spec and you


need to change some code of this file.
In line number 39 add this line so that your app will not be crash.
requirements = python3,kivy==2.1.0,kivymd,pillow
Note: 2.1.0 is your kivy version and it may be different.
You can also change title and logo in source code.
Eighth :
!buildozer -v android debug

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.

General Data Structures


The various data structures in computer science are divided broadly into two categories shown
below.

LINER DATA STRUCTURES


These are the data structures which store the data elements in a sequential manner.
 Array − It is a sequential arrangement of data elements paired with the index of the data
element.
 Linked List − Each data element contains a link to another element along with the data
present in it.
 Stack − It is a data structure which follows only to specific order of operation. LIFO(last in First
Out) or FILO(First in Last Out).
 Queue − It is similar to Stack but the order of operation is only FIFO(First In First Out).
 Matrix − It is two dimensional data structure in which the data element is referred by a pair of
indices.

NON-LINER DATA STRUCTURES


These are the data structures in which there is no sequential linking of data elements. Any pair or
group of data elements can be linked to each other and can be accessed without a strict sequence.
 Binary Tree − It is a data structure where each data element can be connected to maximum
two other data elements and it starts with a root node.
 Heap − It is a special case of Tree data structure where the data in the parent node is either
strictly greater than/ equal to the child nodes or strictly less than it’s child nodes.
 Hash Table − It is a data structure which is made of arrays associated with each other using a
hash function. It retrieves values using keys rather than index from a data element.
 Graph − It is an arrangement of vertices and nodes where some of the nodes are connected to
each other through links.

PYTHON SPECIFIC DATA STRUCTURES


These data structures are specific to python language and they give greater flexibility in storing
different types of data and faster processing in python environment.
 List − It is similar to array with the exception that the data elements can be of different data
Python tutorial
types. You can have both numeric and string data in a python list.
 Tuple − Tuples are similar to lists but they are immutable which means the values in a tuple
cannot be modified they can only be read.
 Dictionary − The dictionary contains Key-value pairs as its data elements.

Implement a stack and queue using List data type:


Stack:
 The stack is a linear data structure.
 Stores items in a Last In First Out (LIFO) or First In Last Out
(FILO) manner.

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!")

You might also like