0% found this document useful (0 votes)
1 views77 pages

Python

Python is a versatile, high-level programming language known for its simplicity and dynamic typing, making it suitable for various applications including web development and scripting. It was created by Guido Van Rossum in the late 1980s, with significant versions released over the years, including Python 3.0 in 2008, which aimed to address fundamental flaws in earlier versions. The language supports multiple programming paradigms, including object-oriented and functional programming, and features a rich set of data types and structures.

Uploaded by

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

Python

Python is a versatile, high-level programming language known for its simplicity and dynamic typing, making it suitable for various applications including web development and scripting. It was created by Guido Van Rossum in the late 1980s, with significant versions released over the years, including Python 3.0 in 2008, which aimed to address fundamental flaws in earlier versions. The language supports multiple programming paradigms, including object-oriented and functional programming, and features a rich set of data types and structures.

Uploaded by

mehal675
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

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's syntax and dynamic typing with its interpreted nature make it an ideal language for scripting and rapid application
development.
Python supports multiple programming pattern, including object-oriented, imperative, and functional or procedural programming
styles.
Python is not intended to work in a particular area, such as web programming. That is why it is known as multipurpose programming
language because it can be used with web, enterprise, 3D CAD, etc.
We don't need to use data types to declare variable because it is dynamically typed so we can write a=10 to assign an integer value
in an integer variable.
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 History and Versions


Python laid its foundation in the late 1980s.
The implementation of Python was started in December 1989 by Guido Van Rossum at CWI in Netherland.
In February 1991, Guido Van Rossum published the code (labeled version 0.9.0) to [Link].
In 1994, Python 1.0 was released with new features like lambda, map, filter, and reduce.
Python 2.0 added new features such as list comprehensions, garbage collection systems.
On December 3, 2008, Python 3.0 (also called "Py3K") was released. It was designed to rectify the fundamental flaw of the language.
ABC programming language is said to be the predecessor of Python language, which was capable of Exception Handling and
interfacing with the Amoeba Operating System.
The following programming languages influence Python:
ABC language.
Modula-3

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.
Variable names can be a group of both the letters and digits, but they have to begin with a letter or an underscore.

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.
The first character of the variable must be an alphabet or underscore ( _ ).
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).
Identifier name must not contain any white-space, or special character (!, @, #, %, ^, &, *).
Identifier name must not be similar to any keyword defined in the language.
Identifier names are case sensitive; for example, my name, and MyName is not the same.
Examples of valid identifiers: a123, _n, n_9, etc.
Examples of invalid identifiers: 1a, n%4, n 9, etc.

Declaring Variable and Assigning Values


Python does not bind us to declare a variable before using it in the application. It allows us to create a variable at the
required time.
We don't need to declare explicitly variable in Python. When we assign any value to the variable, that variable is declared
automatically.
The equal (=) operator is used to assign value to a variable.
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
print(“Vinod")

The Python object creates an integer object and displays it to the console. In the above print statement, we have created a string object. Let's check the
type of it using the Python built-in type() function.
type(“Vinod")
In Python, variables are a symbolic name that is a reference or pointer to an object. The variables are used to denote objects by that name.

a = 50

Variable Names
We have already discussed how to declare the valid variable. Variable names can be any length can have uppercase, lowercase (A to Z, a to z), the digit
(0-9), and underscore character(_). Consider the following example of valid variables names.
name = “Vinod"
age = 20
marks = 80.50

print(name)
print(age)
print(marks)

Multiple Assignment
Python allows us to assign a value to multiple variables in a single statement, which is also known as multiple
assignments.
We can apply multiple assignments in two ways, either by assigning a single value to multiple variables or assigning
multiple values to multiple variables.

x=y=z=50
print(x)
print(y)
print(z)

a,b,c=5,10,15
print a
print b
print c
Python Variable Types
There are two types of variables in Python - Local variable and Global variable

Local Variable
Local variables are the variables that declared inside
the function and have scope within the function.

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.

Python Data Types


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
The variable a holds integer value five and we did not define its type. Python interpreter will automatically interpret
variables a as an integer type.
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.

a=10
b="Hi Python"
c = 10.5
print(type(a))
print(type(b))
print(type(c))

Output:

<type 'int'>
<type 'str'>
<type 'float'>
Standard data types
t

A variable can hold different types of values. For example, a person's name must be stored as a string whereas its id must be stored as an integer.
Python provides various standard data types that define the storage method on each of them. The data types defined in Python are given below.
Numbers
Sequence Type
Boolean
Set
Dictionary

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.

a=5
print("The type of a", type(a)) #int

b = 40.5
print("The type of b", type(b)) #float

c = 1+3j
print("The type of c", type(c)) #complex
print(" c is a complex number", isinstance(1+3j,complex))

Python supports three types of numeric data.


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
Float - Float is used to store floating-point numbers like 1.9, 9.902, 15.2, etc. It is accurate upto 15 decimal points.
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.

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'.
str = "string using double quotes"
print(str)
s = '''''A multiline
string'''
print(s)

str1 = 'hello waytocode' #string str1


str2 = ' how are you' #string str2
print (str1[0:2]) #printing first two character using slice operator
print (str1[4]) #printing 4th character of the string
print (str1*2) #printing the string twice
print (str1 + str2) #printing the concatenation of str1 and str2

List
Python Lists are similar to arrays in C. However, the list can contain data of different types. The items stored in the list are separated
with a comma (,) and enclosed within square brackets [].
We can use slice [:] operators to access the data of the list. The concatenation operator (+) and repetition operator (*) works with
the list in the same way as they were working with the strings.

list1 = [1, "hi", "Python", 2]


#Checking type of given list
print(type(list1))

#Printing the list1


print (list1)

# List slicing
print (list1[3:])

# List slicing
print (list1[0:2])

# List Concatenation using + operator


print (list1 + list1)

# List repetation using * operator


print (list1 * 3)
Tuple
A tuple is similar to the list in many ways. Like lists, tuples also contain the collection of the items of different data types. The items of the tuple are separated with a
comma (,) and enclosed in parentheses ().
A tuple is a read-only data structure as we can't modify the size and value of the items of a tuple.

tup = ("hi", "Python", 2)


# Checking type of tup
print (type(tup))

#Printing the tuple


print (tup)

# Tuple slicing
print (tup[1:])
print (tup[0:1])

# Tuple concatenation using + operator


print (tup + tup)

# Tuple repatation using * operator


print (tup * 3)

# Adding value to tup. It will throw an error.


t[2] = "hi"

Dictionary
Dictionary is an unordered set of a key-value pair of items. It is like an associative array or a hash table where each
key stores a specific value. Key can hold any primitive data type, whereas value is an arbitrary Python object.
The items in the dictionary are separated with the comma (,) and enclosed in the curly braces {}.
d = {1:’vinod', 2:’aashu', 3:’kush', 4:’pooja'}

# Printing dictionary
print (d)

# Accesing value using keys


print("1st name is "+d[1])
print("2nd name is "+ d[4])

print ([Link]())
print ([Link]())
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'.
# Python program to check the boolean type
print(type(True))
print(type(False))
print(false)
Output:

<class 'bool'>
<class 'bool'>
NameError: name 'false' is not defined

Set
Python Set is the unordered collection of the data type. It is iterable, mutable(can modify after creation), and has unique elements.
In set, the order of the elements is undefined; it may return the changed sequence of the element. The set is created by using a
built-in function set(), or a sequence of elements is passed in the curly braces and separated by the comma. It can contain various
types of values.
# Creating Empty set
set1 = set()

set2 = {'James', 2, 3,'Python'}

#Printing Set value


print(set2)

# Adding element to the set

[Link](10)
print(set2)

#Removing element from the set


[Link](2)
print(set2)
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

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.

Consider the following explanation of keywords.


True - It represents the Boolean true, if the given condition is true, then it returns "True". Non-zero values are treated as
true.
False - It represents the Boolean false; if the given condition is false, then it returns "False". Zero value is treated as false
None - It denotes the null value or void. An empty list or Zero can't be treated as None.
and - It is a logical operator. It is used to check the multiple conditions. It returns true if both conditions are true. Consider
the following truth table.

Python Operators
Operators are used to perform operations on variables and values.
Python divides the operators in the following groups:
Arithmetic operators
Assignment operators
Comparison operators
Logical operators
Identity operators
Membership operators
Bitwise operators

Python Arithmetic Operators


Arithmetic operators are used with numeric values to perform common mathematical operations:
• Python Assignment Operators
• Assignment operators are used to assign values to variables:

Python Comparison Operators


Comparison operators are used to compare two values:
Python Logical Operators
Logical operators are used to combine conditional statements:

Python Identity Operators


Identity operators are used to compare the objects, not if they are equal, but if they are actually the same object, with the same
memory location:

Python Membership Operators


Membership operators are used to test if a sequence is presented in an object:

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.

Statement Description

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


condition is true, a block of code (if-block) will be executed.
If - else Statement The if-else statement is similar to if statement except the
fact that, it 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.
Nested if Statement Nested if statements enable us to use if ? else statement
inside an 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.

if expression:
statement
num = int(input("enter the number?"))
if num%2 == 0:
print("Number is even")

Program to print the largest of the three numbers.

a = int(input("Enter a? "));
b = int(input("Enter b? "));
c = int(input("Enter c? "));
if a>b and a>c:
print("a is largest");
if b>a and b>c:
print("b is largest");
if c>a and c>b:
print("c is largest");

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.

if condition:
#block of statements
else:
#another block of statements (else-block)

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


if age>=18:
print("You are eligible to vote !!");
else:
print("Sorry! you have to wait !!");

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


if num%2 == 0:
print("Number is even...")
else:
print("Number is odd...")
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.
if expression 1:
# block of statements
elif expression 2:
# block of statements
elif expression 3:
# block of statements
else:
# block of statements

number = int(input("Enter the number?"))


if number==10:
print("number is equals to 10")
elif number==50:
print("number is equal to 50");
elif number==100:
print("number is equal to 100");
else:
print("number is not equal to 10, 50 or 100");

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.

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.
It provides code re-usability.
Using loops, we do not need to write the same code again and again.
Using loops, we can traverse over the elements of data structures (array or linked lists).
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.
for iterating_var in sequence:
statement(s)

For loop Using Sequence

str = "Python"
for i in str:
print(i)

list = [1,2,3,4,5,6,7,8,9,10]
n=5
for i in list:
c = n*i
print(c)

list = [10,30,23,43,65,12]
sum = 0
for i in list:
sum = sum+i
print("The sum is:",sum)

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.

Syntax:
range(start,stop,step size)

The start represents the beginning of the iteration.


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

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

Program to print table of given number


n = int(input("Enter the number "))
for i in range(1,11):
c = n*i
print(n,"*",i,"=",c)

Program to print even number using step size in range().

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

for i in range(2,n,2):

print(i)
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.
Syntax
for iterating_var1 in sequence: #outer loop
for iterating_var2 in sequence: #inner loop
#block of statements
#Other statements

Nested for loop Program to number pyramid.


# User input for number of rows
rows = int(input("Enter the rows:"))
# Outer loop will print number of rows
for i in range(0,rows+1):
# Inner loop will print number of Astrisk
for j in range(i):
print("*",end = '')
print()

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 statement will not be executed.

for i in range(0,5):
print(i)
else:
print("for loop completely exhausted, since there is no break.")

for i in range(0,5):
print(i)
break;
else:print("for loop is exhausted");
print("The loop is broken due to break statement...came out of the loop")
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.

while expression:
statements

i=1
#The while loop will iterate until condition becomes false.
While(i<=10):
print(i)
i=i+1

Using else with while loop


Python allows us to use the else statement with the while loop also. The else block is executed when the condition given in the while statement becomes false. Like for
loop, if the while loop is broken using break statement, then the else block will not be executed, and the statement present after else block will be executed. The else
statement is optional to use with the while loop.
i=1
while(i<=5):
print(i)
i=i+1
else:
print("The while loop exhausted")

Python break statement


The break is a keyword in python which is used to bring the program control out of the loop. The break statement
breaks the loops one by one, i.e., in the case of nested loops, it breaks the inner loop first and then proceeds to
outer loops. In other words, we can say that break is used to abort the current execution of the program and the
control goes to the next line after the loop.
The break is commonly used in the cases where we need to break the loop for a given condition.

#loop statements
break;
str = "python"
for i in str:
if i == 'o':
break
print(i);
Python continue Statement
The continue statement in Python is used to bring the program control to the beginning of the loop. The continue statement skips the remaining lines of code inside the
loop and start with the next iteration. It is mainly used for a particular condition inside the loop so that we can skip some specific code for a particular [Link]
continue statement in Python is used to bring the program control to the beginning of the loop. The continue statement skips the remaining lines of code inside the loop
and start with the next iteration. It is mainly used for a particular condition inside the loop so that we can skip some specific code for a particular condition.

Syntax
#loop statements
continue
#the code to be skipped

i=0
while(i < 10):
i = i+1
if(i == 5):
continue
print(i)

Pass Statement
The pass statement is a null operation since nothing happens when it is executed. It is used in the cases where a
statement is syntactically needed but we don't want to use any executable statement at its place.
For example, it can be used while overriding a parent class method in the subclass but don't want to give its specific
implementation in the subclass.
Pass is also used where the code will be written somewhere but not yet written in the program file.

i=0
while(i < 10):
i = i+1
if(i == 5):
pass
print(i)
print(i)
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.
The Function helps to programmer to break the program into the smaller part. It organizes the code very effectively and avoids the repetition of the code. As the
program grows, function makes the program more organized.

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.

User-define functions - The user-defined functions are those define by the user to perform the specific task.

Built-in functions - The built-in functions are those functions that are pre-defined in Python.

In this tutorial, we will discuss the user define functions.

Advantage of Functions in Python


There are the following advantages of Python functions.

Using functions, we can avoid rewriting the same logic/code again and again in a program.

We can call Python functions multiple times in a program and anywhere in a program.

We can track a large Python program easily when it is divided into multiple functions.

Reusability is the main achievement of Python functions.

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:

def my_function(parameters):

function_block

return expression

The def keyword, along with the function name is used to define the function.
The identifier rule must follow the function name.
A function accepts the parameter (argument), and they can be optional.
The function block is started with the colon (:), and block statements must be at the same indentation.
The return statement is used to return the value. A function can have only one return

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".
#function definition
def hello_world():
print("hello world")
# function calling
hello_world()
def sum (a,b):
return a+b;

#taking values from the user


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

#printing the sum of a and b


print("Sum = ",sum(a,b))

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.
#defining the function
def func (name):
print("Hi ",name)
#calling the function
func(“aashu")

Types of arguments
There may be several types of arguments which can be passed at the time of function call.
Required arguments
Keyword arguments
Default arguments
Variable-length arguments

Required Arguments
Till now, we have learned about function calling in Python. 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.

def func(name):
message = "Hi "+name
return message
name = input("Enter the name:")
print(func(name))

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.
def printme(name,age=22):
print("My name is",name,"and age is",age)
printme(name = "john")
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 >.
def printme(*names):
print("type of passed argument is ",type(names))
print("printing the passed arguments...")
for name in names:
print(name)
printme("john","David","smith","nick")

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.
#function func is called with the name and message as the keyword arguments
def func(name,message):
print("printing the message with",name,"and ",message)

#name and message is copied with the values John and hello respectively
func(name = "John",message="hello")

Scope of variables
The scopes of the variables depend upon the location where the variable is being declared. The variable declared in one part of the program may not be accessible to the
other parts.
In python, the variables are defined with the two types of scopes.
Global variables
Local variables
The variable defined outside any function is known to have a global scope, whereas the variable defined inside a function is known to have a local scope.

Example 1 Local Variable

def print_message():
message = "hello !! I am going to print a message." # the variable message is local to the function itself
print(message)
print_message()
print(message) # this will cause an error since a local variable cannot be accessible here.

Example 2 Global Variable

def calculate(*args):
sum=0
for arg in args:
sum = sum +arg
print("The sum is",sum)
sum=0
calculate(10,20,30) #60 will be printed as the sum
print("Value of sum outside the function:",sum) # 0 will be printed Output:
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. There are several built-in
functions in Python which are listed below:
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
# integer number
integer = -20
print('Absolute value of -40 is:', abs(integer))

# floating number
floating = -20.83
print('Absolute value of -40.83 is:', abs(floating))

Python all() Function


The python all() function accepts an iterable object (such as list, dictionary, etc.).
It returns true if all items in passed iterable are true. Otherwise, it returns False.
If the iterable object is empty, the all() function returns True.

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.
x = 10
y = bin(x)
print (y)

Python bool()
The python bool() converts a value to boolean(True or False) using the standard truth testing procedure.
test1 = []
print(test1,'is',bool(test1))
test1 = [0]
print(test1,'is',bool(test1))
test1 = 0.0
print(test1,'is',bool(test1))
test1 = None
print(test1,'is',bool(test1))
test1 = True
print(test1,'is',bool(test1))
test1 = 'Easy string'
print(test1,'is',bool(test1))

Python bytes()
The python bytes() in Python is used for returning a bytes object. It is an immutable version of the bytearray() function.
It can create empty bytes object of the specified size.
string = "Hello World."
array = bytes(string, 'utf-8')
print(array)
Python callable() Function
A python callable() function in Python is something that can be called. This built-in function checks and returns true if the object passed appears to be callable, otherwise false.
x=8
print(callable(x))

Python compile() Function


The python compile() function takes source code as input and returns a code object which can later be executed by exec() function.
# compile string source to code
code_str = 'x=5\ny=10\nprint("sum =",x+y)'
code = compile(code_str, '[Link]', 'exec')
print(type(code))
exec(code)
exec(x)

Python exec() Function


The python exec() function is used for the dynamic execution of Python program which can either be a string or object code and it accepts large blocks of code, unlike the eval() function
which only accepts a single expression.
x=8
exec('print(x==8)')
exec('print(x+4)')
Python sum() Function
As the name says, python sum() function is used to get the sum of numbers of an iterable, i.e., list.
s = sum([1, 2,4 ])
print(s)

s = sum([1, 2, 4], 10)


print(s)

Python any() Function

The python any() function returns true if any item in an iterable is true. Otherwise, it returns False.
l = [4, 3, 2, 0]
print(any(l))

l = [0, False]
print(any(l))

l = [0, False, 5]
print(any(l))

l = []
print(any(l))

Python ascii() Function

The python ascii() function returns a string containing a printable representation of an object and escapes the non-ASCII characters in the string using \x, \u or \U
escapes.
normalText = 'Python is interesting'
print(ascii(normalText))

otherText = 'Pythön is interesting'


print(ascii(otherText))

print('Pyth\xf6n is interesting')
Python bytearray()
The python bytearray() returns a bytearray object and can convert objects into bytearray objects, or create an empty bytearray object of the specified size.
string = "Python is a programming language."

# string with encoding 'utf-8'


arr = bytearray(string, 'utf-8')
print(arr)

Python eval() Function


The python eval() function parses the expression passed to it and runs python expression(code) within the program.
x=8
print(eval('x + 1'))

Python float()
The python float() function returns a floating-point number from a number or string.
# for integers
print(float(9))

# for floats
print(float(8.19))

# for string floats


print(float("-24.27"))

# for string floats with whitespaces


print(float(" -17.19\n"))

# string float error


print(float("xyz"))

Python format() Function


The python format() function returns a formatted representation of the given value.
# d, f and b are a type
# integer
print(format(123, "d"))
# float arguments
print(format(123.4567898, "f"))
# binary format
print(format(12, "b"))

Python frozenset()
The python frozenset() function returns an immutable frozenset object initialized with elements from the given iterable.
# tuple of letters
letters = ('m', 'r', 'o', 't', 's')

fSet = frozenset(letters)
print('Frozen set is:', fSet)
print('Empty frozen set is:', frozenset())

Python getattr() Function


The python getattr() function returns the value of a named attribute of an object. If it is not found, it returns the default value.
class Details:
age = 22
name = "Phill"
details = Details()
print('The age is:', getattr(details, "age"))
print('The age is:', [Link])
Python globals() Function
The python globals() function returns the dictionary of the current global symbol table.
A Symbol table is defined as a data structure which contains all the necessary information about the program. It includes variable names, methods,
classes, etc.
age = 22

globals()['age'] = 22
print('The age is:', age)

Python hasattr() Function


The python any() function returns true if any item in an iterable is true, otherwise it returns False
l = [4, 3, 2, 0]
print(any(l))

l = [0, False]
print(any(l))

l = [0, False, 5]
print(any(l))

l = []
print(any(l))

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.
# list of numbers
list = [1,2,3,4,5]

listIter = iter(list)

# prints '1'
print(next(listIter))

# prints '2'
print(next(listIter))

# prints '3'
print(next(listIter))

# prints '4'
print(next(listIter))

# prints '5'
print(next(listIter))

Python len() Function


The python len() function is used to return the length (the number of items) of an object.
strA = 'Python'
print(len(strA))
Python list()
The python list() creates a list in python.
# empty list
print(list())

# string
String = 'abcde'
print(list(String))

# tuple
Tuple = (1,2,3,4,5)
print(list(Tuple))
# list
List = [1,2,3,4,5]
print(list(List))

Python locals() Function


The python locals() method updates and returns the dictionary of the current local symbol table.
A Symbol table is defined as a data structure which contains all the necessary information about the program. It includes variable names, methods, classes, etc.
def localsAbsent():
return locals()

def localsPresent():
present = True
return locals()

print('localsNotPresent:', localsAbsent())
print('localsPresent:', localsPresent())

Python map() Function


The python map() function is used to return a list of results after applying a given function to each item of an iterable(list, tuple etc.).
def calculateAddition(n):
return n+n

numbers = (1, 2, 3, 4)
result = map(calculateAddition, numbers)
print(result)

# converting map object to set


numbersAddition = set(result)
print(numbersAddition)

Python memoryview() Function


The python memoryview() function returns a memoryview object of the given argument.
#A random bytearray
randomByteArray = bytearray('ABC', 'utf-8')

mv = memoryview(randomByteArray)

# access the memory view's zeroth index


print(mv[0])

# It create byte from memory view


print(bytes(mv[0:2]))

# It create list from memory view


print(list(mv[0:3]))
Python object()
The python object() returns an empty object. It is a base for all the classes and holds the built-in properties and methods which are default for all the classes.
python = object()

print(type(python))
print(dir(python))

Python open() Function


The python open() function opens the file and returns a corresponding file object.
# opens [Link] file of the current directory
f = open("[Link]")
# specifying full path
f = open("C:/Python33/[Link]")

Python chr() Function


Python chr() function is used to get a string representing a character which points to a Unicode code integer. For example, chr(97) returns the string 'a'. This function
takes an integer argument and throws an error if it exceeds the specified range. The standard range of the argument is from 0 to 1,114,111.
# Calling function
result = chr(102) # It returns string representation of a char
result2 = chr(112)
# Displaying result
print(result)
print(result2)
# Verify, is it string type?
print("is it string type:", type(result) is str)

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() function example
# Calling function
a = complex(1) # Passing single parameter
b = complex(1,2) # Passing both parameters
# Displaying result
print(a)
print(b)

Python delattr() Function

Python delattr() function is used to delete an attribute from a class. It takes two parameters, first is an object of the class and second is an attribute which we want to
delete. After deleting the attribute, it no longer available in the class and throws an error if try to call it using the class object.
class Student:
id = 101
name = “vinod"
email = “vinod@[Link]"
# Declaring function
def getinfo(self):
print([Link], [Link], [Link])
s = Student()
[Link]()
delattr(Student,'course') # Removing attribute which is not available
[Link]() # error: throws an error
Python dir() Function

Python dir() function returns the list of names in the current local scope. If the object on which method is called has a method named __dir__(), this method will be
called and must return the list of attributes. It takes a single object type argument.
# Calling function
att = dir()
# Displaying result
print(att)

Python divmod() Function

Python divmod() function is used to get remainder and quotient of two numbers. This function takes two numeric arguments and returns a tuple. Both arguments are
required and numeric
# Python divmod() function example
# Calling function
result = divmod(10,2)
# Displaying result
print(result)

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 the elements in sequence either through a loop or next() method.
# Calling function
result = enumerate([1,2,3])
# Displaying result
print(result)
print(list(result))

Python dict()

Python dict() function is a constructor which creates a dictionary. Python dictionary provides three different constructors to create a dictionary:
If no argument is passed, it creates an empty dictionary.
If a positional argument is given, a dictionary is created with the same key-value pairs. Otherwise, pass an iterable object.
If keyword arguments are given, the keyword arguments and their values are added to the dictionary created from the positional argument.
# Calling function
result = dict() # returns an empty dictionary
result2 = dict(a=1,b=2)
# Displaying result
print(result)
print(result2)

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
def filterdata(x):
if x>5:
return x
# Calling function
result = filter(filterdata,(1,2,6))
# Displaying result
print(list(result))
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 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.
# Calling function
result = hash(21) # integer value
result2 = hash(22.2) # decimal value
# Displaying result
print(result)
print(result2)

Python help() Function


Python help() function is used to get help related to the object passed during the call. It takes an optional parameter and returns help information. If no argument is given, it shows the
Python help console. It internally calls python's help function.
# Calling function
info = help() # No argument
# Displaying result
print(info)

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.
# Calling function
small = min(2225,325,2025) # returns smallest element
small2 = min(1000.25,2025.35,5625.36,10052.50)
# Displaying result
print(small)
print(small2)

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 aniterable object as an argument and returns a new set object.

# Calling function

result = set() # empty set

result2 = set('12')

result3 = set(‘waytocode')

# Displaying result

print(result)

print(result2)

print(result3)

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
[Link]() function.

# Calling function

result = hex(1)

# integer value

result2 = hex(342)

# Displaying result

print(result)

print(result2)

Python id() Function

Python id() function returns the identity of an object. This is an integer which is guaranteed to be unique. This function takes an argument as an object and returns a unique integer number which represents identity. Two objects with
non-overlapping lifetimes may have the same id() value.

# Calling function

val = id(" waytocode ") # string object

val2 = id(1200) # integer object

val3 = id([25,336,95,236,92,3225]) # List object

# Displaying result

print(val)

print(val2)

print(val3)
Python setattr() Function
Python setattr() function is used to set a value to the object's attribute. It takes three arguments, i.e., an object, a string, and an arbitrary value, and returns none. It is
helpful when we want to add a new attribute to an object and set a value to it.
class Student:
id = 0
name = ""

def __init__(self, id, name):


[Link] = id
[Link] = name

student = Student(102,“vinod")
print([Link])
print([Link])
#print([Link]) product error
setattr(student, 'email’,’vinod@[Link]') # adding new attribute
print([Link])

Python slice() Function

Python slice() function is used to get a slice of elements from the collection of elements. Python provides two overloaded slice functions. The first function takes a single argument while the second function
takes three arguments and returns a slice object. This slice object can be used to get a subsection of the collection.

# Calling function

result = slice(5) # returns slice object

result2 = slice(0,5,3) # returns slice object

# Displaying result

print(result)

print(result2)

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.
str = “waytocode" # declaring string
# Calling function
sorted1 = sorted(str) # sorting string
# Displaying result
print(sorted1)

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.

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

# Calling function

item = next(number)

# Displaying result

print(item)

# second item

item = next(number)

print(item)

# third item

item = next(number)

print(item)

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. It throws an errorEOFError if EOF is read.

val = input("Enter a value: ")

# Displaying result

print("You entered:",val)
Python int() Function
Python int() function is used to get an integer value. It returns an expression converted into an integer number. If the argument is a floating-point, the conversion
truncates the number. If the argument is outside the integer range, then it converts the number into a long type.
If the number is not a number or if a base is given, the number must be a string.
val = int(10) # integer value
val2 = int(10.52) # float value
val3 = int('10') # string value
# Displaying result
print("integer values :",val, val2, val3)

Python isinstance() Function


Python isinstance() function is used to check whether the given object is an instance of that class. If the object belongs to the class, it returns true. Otherwise returns
False. It also returns true if the class is a subclass.
The isinstance() function takes two arguments, i.e., object and classinfo, and then it returns either True or False.
class Student:
id = 101
name = "John"
def __init__(self, id, name):
[Link]=id
[Link]=name

student = Student(1010,"John")
lst = [12,34,5,6,767]
# Calling function
print(isinstance(student, Student)) # isinstance of Student class
print(isinstance(lst, Student))

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.
val = oct(10)
# Displaying result
print("Octal value of 10:",val)

Python ord() Function


The python ord() function returns an integer representing Unicode code point for the given Unicode character.
print(ord('8'))
# Code point of an alphabet
print(ord('R'))
# Code point of a character
print(ord('&'))

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.
# positive x, positive y (x**y)
print(pow(4, 2))

# negative x, positive y
print(pow(-4, 2))

# positive x, negative y (x**-y)


print(pow(4, -2))

# negative x, negative y
print(pow(-4, -2))
Python print() Function

The python print() function prints the given object to the screen or other standard output devices.
print("Python is programming language.")

x=7
# Two objects passed
print("x =", x)

y=x
# Three objects passed
print('x =', x, '= y')

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.
# empty range
print(list(range(0)))

# using the range(stop)


print(list(range(4)))

# using the range(start, stop)


print(list(range(1,7 )))

Python reversed() Function


The python reversed() function returns the reversed iterator of the given sequence.
# for string
String = 'Java'
print(list(reversed(String)))

# for tuple
Tuple = ('J', 'a', 'v', 'a')
print(list(reversed(Tuple)))

# for range
Range = range(8, 12)
print(list(reversed(Range)))

# for list
List = [1, 2, 7, 5]
print(list(reversed(List)))

Python round() Function


The python round() function rounds off the digits of a number and returns the floating point number.
# for integers
print(round(10))

# for floating point


print(round(10.8))

# even choice
print(round(6.6))
Python issubclass() Function

The python issubclass() function returns true if object argument(first argument) is a subclass of second class(second argument).
class Rectangle:
def __init__(rectangleType):
print('Rectangle is a ', rectangleType)

class Square(Rectangle):
def __init__(self):
Rectangle.__init__('square')

print(issubclass(Square, Rectangle))
print(issubclass(Square, list))
print(issubclass(Square, (list, Rectangle)))
print(issubclass(Rectangle, (list, Rectangle)))

Python str

The python str() converts a specified value into a string


str('4')

Python tuple() Function

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


t1 = tuple()
print('t1=', t1)
# creating a tuple from a list
t2 = tuple([1, 6, 9])
print('t2=', t2)
# creating a tuple from a string
t1 = tuple('Java')
print('t1=',t1)
# creating a tuple from a dictionary
t1 = tuple({4: 'four', 5: 'five'})
print('t1=',t1)

Python type()

The python type() returns the type of the specified object if a single argument is passed to the type() built in function. If three arguments are passed, then it returns a
new type object.
List = [4, 5]
print(type(List))
Dict = {4: 'four', 5: 'five'}
print(type(Dict))
class Python:
a=0
InstanceOfPython = Python()
print(type(InstanceOfPython))
Python vars() function
The python vars() function returns the __dict__ attribute of the given object.
class Python:
def __init__(self, x = 7, y = 9):
self.x = x
self.y = y

InstanceOfPython = Python()
print(vars(InstanceOfPython))

Python zip() Function


The python zip() Function returns a zip object, which maps a similar index of multiple containers. It takes iterables (can be zero or more), makes it an iterator that aggregates the
elements based on iterables passed, and returns an iterator of tuples.
numList = [4,5, 6]
strList = ['four', 'five', 'six']

# No iterables are passed


result = zip()

# Converting itertor to list


resultList = list(result)
print(resultList)

# Two iterables are passed


result = zip(numList, strList)

# Converting itertor to set


resultSet = set(result)
print(resultSet)

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.
Syntax
lambda arguments: expression
Example 1
# a is an argument and a+10 is an expression which got evaluated and returned.
x = lambda a:a+10
# Here we are printing the function object
print(x)
print("sum = ",x(20))

In the above example, we have defined the lambda a: a+10 anonymous function where a is an argument and a+10 is an expression. The given expression gets evaluated and returned the result. The above lambda
function is same as the normal function.

def x(a):
return a+10
print(sum = x(10))

Using lambda function with map()


The map() function in Python accepts a function and a list. It gives a new list which contains all modified items returned by the function for each item.
Consider the following example of map() function.
#program to filter out the list which contains odd numbers
lst = (10,20,30,40,50,60)
square_list = list(map(lambda x:x**2,lst)) # the tuple contains all the items of the list for which the lambda function evaluates to true
print(square_tuple)
Python Modules
A python module can be defined as a python program file which contains a python code including python functions, class, or variables. In other words, we
can say that our python code file saved with the extension (.py) is treated as the module. We may have a runnable code inside the python module.
Modules in Python provides us the flexibility to organize the code in a logical way.
To use the functionality of one module into another, we must have to import the specific module.
Example
In this example, we will create a module named as [Link] which contains a function func that contains a code to print some message on the console.
Let's create the module named as [Link].
#displayMsg prints a message to the name being passed.
def displayMsg(name)
print("Hi "+name);
Here, we need to include this module into our main module to call the method displayMsg() defined in the module named file.
Loading the module in our python code
We need to load the module in our python code to use its functionality. Python provides two types of statements as defined below.
The import statement
The from-import statement
The import statement
The import statement is used to import all the functionality of one module into another. Here, we must notice that we can use the functionality of any
python source file by importing that file as the module into another python source file.
We can import multiple modules with a single import statement, but a module is loaded once regardless of the number of times, it has been imported into
our file.
The syntax to use the import statement is given below.
import module1,module2,........ module n

Example:
import file;
name = input("Enter the name?")
[Link](name)

The from-import statement


Instead of importing the whole module into the namespace, python provides the flexibility to import only the specific attributes of a module. This can be done by using from? import
statement. The syntax to use the from-import statement is given below.
from < module-name> import <name 1>, <name 2>..,<name n>

Consider the following module named as calculation which contains three functions as summation, multiplication, and divide.

[Link]:
#place the code in the [Link]
def summation(a,b):
return a+b
def multiplication(a,b):
return a*b;
def divide(a,b):
return a/b;

[Link]:
from calculation import summation
#it will import only the summation() from [Link]
a = int(input("Enter the first number"))
b = int(input("Enter the second number"))
print("Sum = ",summation(a,b)) #we do not need to specify the module name while accessing summation()
Python File Handling

Sometimes, it is not enough to only display the data on the console. The data to be displayed may be very large, and only a limited amount of data can be displayed on
the console since the memory is volatile, it is impossible to recover the programmatically generated data again and again.
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.
The file-handling implementation is slightly lengthy or complicated in the other programming language, but it is easier and shorter in Python.
In 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.
Open a file
Read or write - Performing operation
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:

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

#opens the file [Link] in read mode


fileptr = open("[Link]","r")

if fileptr:
print("file is opened successfully")

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

[Link]()

# opens the file [Link] in read mode


fileptr = open("[Link]","r")

if fileptr:
print("file is opened successfully")

#closes the opened file


[Link]()

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.
# open the [Link] in append mode. Create a new file if no such file exists.
fileptr = open("[Link]", "w")

# appending the content to the file


[Link]('''''Python is the modern day language. It makes things so simple.
It is the fastest-growing programing language''')

# closing the opened the file


[Link]()

Example 2

#open the [Link] in write mode.


fileptr = open("[Link]","a")

#overwriting the content of the file


[Link](" Python has an easy syntax and user-friendly interaction.")

#closing the opened file


[Link]()
We can see that the content of the file is modified. We have opened the file in a mode and it appended the content in the
existing [Link].
To read a file using the Python script, the Python provides the read() method. The read() method reads a string from the file. It can
read the data in the text as well as a binary format.

#open the [Link] in read mode. causes error if no such file exists.
fileptr = open("[Link]","r")
#stores all the data of the file into the variable content
content = [Link](10)
# prints the type of the data stored in the file
print(type(content))
#prints the content of the file
print(content)
#closes the opened file
[Link]()

Read file through for loop


#open the [Link] in read mode. causes an error if no such file exists.
fileptr = open("[Link]","r");
#running a for loop
for i in fileptr:
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.
Consider the following example which contains a function readline() that reads the first line of our file "[Link]" containing three lines.
Reading lines using readline() function

#open the [Link] in read mode. causes error if no such file exists.
fileptr = open("[Link]","r");
#stores all the data of the file into the variable content
content = [Link]()
content1 = [Link]()
#prints the content of the file
print(content)
print(content1)
#closes the opened file
[Link]()

Reading Lines Using readlines() function

#open the [Link] in read mode. causes error if no such file exists.
fileptr = open("[Link]","r");
#stores all the data of the file into the variable content
content = [Link]()
#prints the content of the file
print(content)
#closes the opened file
[Link]()
Creating a new file
The new file can be created by using one of the following access modes with the function open().
x: it creates a new file with the specified name. It causes an error a file exists with the same name.
a: It creates a new file with the specified name if no such file exists. It appends the content to the file if the file already exists with the specified name.
w: It creates a new file with the specified name if no such file exists. It overwrites the existing file.
#open the [Link] in read mode. causes error if no such file exists.
fileptr = open("[Link]","x")
print(fileptr)
if fileptr:
print("File created successfully")

Python OS module
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 name.
import os

#rename [Link] to [Link]


[Link]("[Link]","[Link]"

Removing the file


The os module provides the remove() method which is used to remove the specified file.
import os;
#deleting the file named [Link]
[Link]("[Link]")

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 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.
ZeroDivisionError: Occurs when a number is divided by zero.
NameError: It occurs when a name is not found. It may be local or global.
IndentationError: If incorrect indentation is given.
IOError: It occurs when Input Output operation fails.
EOFError: It occurs when the end of the file is reached, and yet operations are being performed.
The problem without handling exceptions
As we have already discussed, the exception is an abnormal condition that halts the execution of the program.
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.
Example

a = int(input("Enter a:"))
b = int(input("Enter b:"))
c = a/b
print("a/b = %d" %c)

#other code:
print("Hi I am other part of the program")
Output:

Enter a:10
Enter b:0
Traceback (most recent call last):
File "[Link]", 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.

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
try:
#block of code

except Exception1:
#block of code

except Exception2:
#block of code

#other code

Example 1

try:
a = int(input("Enter a:"))
b = int(input("Enter b:"))
c = a/b
except:
print("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.
try:
#block of code

except Exception1:
#block of code

else:
#this code executes if no except block is executed

Example 2

try:
a = int(input("Enter a:"))
b = int(input("Enter b:"))
c = a/b
print("a/b = %d"%c)
# Using Exception with except statement. If we print(Exception) it will return exception class
except Exception:
print("can't divide by zero")
print(Exception)
else:
print("Hi I am else block")

The except statement with no exception


Python provides the flexibility not to specify the name of exception with the exception statement.

Example

try:
a = int(input("Enter a:"))
b = int(input("Enter b:"))
c = a/b;
print("a/b = %d"%c)
except:
print("can't divide by zero")
else:
print("Hi I am else block")

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.
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("can't divide by zero")
print(e)
else:
print("Hi I am else block")
Points to remember
Python facilitates us to not specify the exception with the except statement.
We can declare multiple exceptions in the except statement since the try block may contain the statements which throw the different type of exceptions.
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.
The statements that don't throw the exception should be placed inside the else block.
try:
#this will throw an exception if the file doesn't exist.
fileptr = open("[Link]","r")
except IOError:
print("File not found")
else:
print("The file opened successfully")
[Link]()

Declaring Multiple Exceptions


The Python allows us to declare the multiple exceptions with the except clause. Declaring multiple exceptions is useful in the cases where a try block throws multiple
exceptions. The syntax is given below.
Syntax
try:
#block of code

except (<Exception 1>,<Exception 2>,<Exception 3>,...<Exception n>)


#block of code

else:
#block of code

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
Syntax
try:
# block of code
# this may throw an exception
finally:
# block of code
# this will always be executed

Example

try:

fileptr = open("[Link]","r")

try:

[Link]("Hi I am good")

finally:

[Link]()

print("file closed")

except:

print("Error")
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 execution of the
program.
Syntax
raise Exception_class,<value>

Points to remember
To raise an exception, the raise statement is used. The exception class name follows it.
An exception can be provided with a value that can be given in the parenthesis.
To access the value "as" keyword is used. "e" is used as a reference variable which stores the value of the exception.
We can pass the value to an exception to specify the exception type.
try:
age = int(input("Enter the age:"))
if(age<18):
raise ValueError
else:
print("the age is valid")
except ValueError:
print("The age is not valid")

try:
num = int(input("Enter a positive integer: "))
if(num <= 0):
# we can pass the message in the raise statement
raise ValueError("That is a negative number!")
except ValueError as e:
print(e)

Custom Exception
The Python allows us to create our exceptions that can be raised from the program and caught using the except clause. However, we suggest you read this
section after visiting the Python object and classes.
class ErrorInCode(Exception):
def __init__(self, data):
[Link] = data
def __str__(self):
return repr([Link])

try:
raise ErrorInCode(2000)
except ErrorInCode as ae:
print("Received error:", [Link])
Python Date and time
Python provides the datetime module work with real dates and times. In real-world applications, we need to work with
the date and time. Python enables us to schedule our Python script to run at a particular timing.
In Python, the date is not a data type, but we can work with the date objects by importing the module named with
datetime, time, and calendar.

The datetime classes are classified in the six main classes.


date - It is a naive ideal date. It consists of the year, month, and day as attributes.
time - It is a perfect time, assuming every day has precisely 24*60*60 seconds. It has hour, minute, second,
microsecond, and tzinfo as attributes.
datetime - It is a grouping of date and time, along with the attributes year, month, day, hour, minute, second,
microsecond, and tzinfo.
timedelta - It represents the difference between two dates, time or datetime instances to microsecond resolution.
tzinfo - It provides time zone information objects.
timezone - It is included in the new version of Python. It is the class that implements the tzinfo abstract base class.

Tick
In Python, the time instants are counted since 12 AM, 1st January 1970. The function time() of the module time returns
the total number of ticks spent since 12 AM, 1st January 1970. A tick can be seen as the smallest unit to measure the
time.

import time;
#prints the number of ticks spent since 12 AM, 1st January 1970
print([Link]())
Output:
1585928913.6519969

How to get the current time?


The localtime() functions of the time module are used to get the current time tuple. Consider the following example.

import time;
#returns a time tuple
print([Link]([Link]()))
Output:

time.struct_time(tm_year=2020, tm_mon=4, tm_mday=3, tm_hour=21, tm_min=21, tm_sec=40, tm_wday=4,


tm_yday=94, tm_isdst=0)
Time tuple
The time is treated as the tuple of 9 numbers. Let's look at the members of the time tuple.

Index Attribute Values


0 Year 4 digit (for example 2018)
1 Month 1 to 12
2 Day 1 to 31
3 Hour 0 to 23
4 Minute 0 to 59
5 Second 0 to 60
6 Day of weak 0 to 6
7 Day of year 1 to 366
8 Daylight savings -1, 0, 1 , or -1

Getting formatted time


The time can be formatted by using the asctime() function of the time module. It returns the formatted time for the time tuple being
passed.

import time
#returns the formatted time
print([Link]([Link]([Link]())))

Python sleep time


The sleep() method of time module is used to stop the execution of the script for a given amount of time. The output will be delayed
for the number of seconds provided as the float.
import time
for i in range(0,5):
print(i)
#Each element will be printed after 1 second
[Link](1)
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.
import datetime
#returns the current datetime object
print([Link]())

Creating date objects


We can create the date objects bypassing the desired date in the datetime constructor for which the date objects are to
be created.
import datetime
#returns the datetime object for the specified date
print([Link](2020,04,04))
Output:

2020-04-04 00:00:00

We can also specify the time along with the date to create the datetime object. Consider the following example.

import datetime
#returns the datetime object for the specified time

print([Link](2020,4,4,1,26,40))
Output:
2020-04-04 01:26:40

Comparison of two dates


We can compare two dates by using the comparison operators like >, >=, <, and <=.
from datetime import datetime as dt
#Compares the time. If the time is in between 8AM and 4PM, then it prints working hours otherwise it prints fun hours
if dt([Link]().year,[Link]().month,[Link]().day,8)<[Link]()<dt([Link]().year,[Link]().month,[Link]().day,16):
print("Working hours....")
else:
print("fun hours")
The calendar module
Python provides a calendar object that contains various methods to work with the calendars.
import calendar;
cal = [Link](2020,3)
#printing the calendar of December 2018
print(cal)

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.
import calendar
#printing the calendar of the year 2019
s = [Link](2020)

Python Regular Expressions


The regular expressions can be defined as the sequence of characters which are used to search for a pattern in a string. The module
re provides the support to use regex in the python program. The re module throws an exception if there is some error while using the
regular expression.
The re module must be imported to use the regex functionalities in python.
import re

Regex Functions

1 match This method matches the regex pattern in the string with the optional flag. It returns true if a match is found in the
string otherwise it returns false.
2 search This method returns the match object if there is a match found in the string.
3 findall It returns a list that contains all the matches of a pattern in the string.
4 split Returns a list in which the string has been split in each match.
5 sub Replace one or many matches in the string.
Forming a regular expression
A regular expression can be formed by using the mix of meta-characters, special sequences, and sets.

Meta-Characters
Metacharacter is a character with the specified meaning.
Metacharacter Description Example
[] It represents the set of characters. "[a-z]"
\ It represents the special sequence. "\r"
. It signals that any character is present at some specific place. "Ja.v."
^ It represents the pattern present at the beginning of the string. "^Java"
$ It represents the pattern present at the end of the string. "point"
* It represents zero or more occurrences of a pattern in the string. "hello*"
+ It represents one or more occurrences of a pattern in the string. "hello+"
{} The specified number of occurrences of a pattern the string. "java{2}"
| It represents either this or that character is present. “way|code"
() Capture and group

Special Sequences
Special sequences are the sequences containing \ followed by one of the characters.

Character Description
\A It returns a match if the specified characters are present at the beginning of the string.
\b It returns a match if the specified characters are present at the beginning or the end of the string.
\B It returns a match if the specified characters are present at the beginning of the string but not at the end.
\d It returns a match if the string contains digits [0-9].
\D It returns a match if the string doesn't contain the digits [0-9].
\s It returns a match if the string contains any white space character.
\S It returns a match if the string doesn't contain any white space character.
\w It returns a match if the string contains any word characters.
\W It returns a match if the string doesn't contain any word.
\Z Returns a match if the specified characters are at the end of the string.
Sets
A set is a group of characters given inside a pair of square brackets. It represents the special meaning.

SN Set Description
1 [arn] Returns a match if the string contains any of the specified characters in the set.
2 [a-n] Returns a match if the string contains any of the characters between a to n.
3 [^arn] Returns a match if the string contains the characters except a, r, and n.
4 [0123] Returns a match if the string contains any of the specified digits.
5 [0-9] Returns a match if the string contains any digit between 0 and 9.
6 [0-5][0-9] Returns a match if the string contains any digit between 00 and 59.
10 [a-zA-Z] Returns a match if the string contains any alphabet (lower-case or upper-case).

The findall() function


This method returns a list containing a list of all matches of a pattern within the string. It returns the patterns in the order they
are found. If there are no matches, then an empty list is returned.

import re
str = "How are you. How is everything"
matches = [Link]("How", str)

print(matches)

print(matches)

The match object


The match object contains the information about the search and the output. If there is no match found, the None object is
returned.

import re

str = "How are you. How is everything"


matches = [Link]("How", str)
print(type(matches))
print(matches) #matches is the search object
The Match object methods
There are the following methods associated with the Match object.

span(): It returns the tuple containing the starting and end position of the match.
string(): It returns a string passed into the function.
group(): The part of the string is returned where the match is found.

import re

str = "How are you. How is everything"


matches = [Link]("How", str)
print([Link]())
print([Link]())
print([Link])

Python List Comprehension


List Comprehension is defined as an elegant way to define, create a list in Python and consists of brackets that contains an
expression followed by for clause. It is efficient in both computationally and in terms of coding space and time.

Signature
The list comprehension starts with '[' and ']'.
[ expression for item in list if conditional ]

letters = []
for letter in 'Python':
[Link](letter)
print(letters)

letters = [ letter for letter in 'Python' ]


print( letters)

x = {'chrome': 'browser', 'Windows': 'OS', 'C': 'language'}


x['mouse'] = 'hardware'
print(x['Windows'])
Python Arrays
An array is defined as a collection of items that are stored at contiguous memory locations. It is a container which can hold a fixed number of items, and
these items should be of the same type. An array is popular in most programming languages like C/C++, JavaScript, etc.

Array is an idea of storing multiple items of the same type together and it makes easier to calculate the position of each element by simply adding an
offset to the base value. A combination of the arrays could save a lot of time by reducing the overall size of the code. It is used to store multiple values in
single variable. If you have a list of items that are stored in their corresponding variables like this:

car1 = “aashu"
car2 = “vinod"
car3 = “jack"

If you want to loop through cars and find a specific one, you can use the array.

The array can be handled in Python by a module named array. It is useful when we have to manipulate only specific data values. Following are the
terms to understand the concept of an array:

Element - Each item stored in an array is called an element.


Index - The location of an element in an array has a numerical index, which is used to identify the position of the element.

Array Representation
An array can be declared in various ways and different languages. The important points that should be considered are as follows:

Index starts with 0.


We can access each element via its index.
The length of the array defines the capacity to store the elements.
Array operations
Some of the basic operations supported by an array are as follows:

Traverse - It prints all the elements one by one.


Insertion - It adds an element at the given index.
Deletion - It deletes an element at the given index.
Search - It searches an element using the given index or by the value.
Update - It updates an element at the given index.

The Array can be created in Python by importing the array module to the python program.
from array import *
arrayName = array(typecode, [initializers])
Accessing array elements

We can access the array elements using the respective indices of those elements.

import array as arr


a = [Link]('i', [2, 4, 6, 8])
print("First element:", a[0])
print("Second element:", a[1])
print("Second last element:", a[-1])

How to change or add elements


Arrays are mutable, and their elements can be changed in a similar way like lists.

import array as arr


numbers = [Link]('i', [1, 2, 3, 5, 7, 10])
# changing first element
numbers[0] = 0
print(numbers) # Output: array('i', [0, 2, 3, 5, 7, 10])

# changing 3rd to 5th element


numbers[2:5] = [Link]('i', [4, 6, 8])
print(numbers) # Output: array('i', [0, 2, 4, 6, 8, 10])

Why to use arrays in Python?


A combination of arrays saves a lot of time. The array can reduce the overall size of the code.
How to delete elements from an array?
The elements can be deleted from an array using Python's del statement. If we want to delete any value from the array, we can do that by using the
indices of a particular element.
import array as arr
number = [Link]('i', [1, 2, 3, 3, 4])
del number[2] # removing third element
print(number) # Output: array('i', [1, 2, 3, 4])

Finding the length of an array


The length of an array is defined as the number of elements present in an array. It returns an integer value that is equal to the total number of the
elements present in that array.
len(array_name)

Array Concatenation
We can easily concatenate any two arrays using the + symbol.
a=[Link]('d',[1.1 , 2.1 ,3.1,2.6,7.8])
b=[Link]('d',[3.7,8.6])
c=[Link]('d')
c=a+b
print("Array c = ",c)
Python Stack and Queue
Data structure organizes the storage in computers so that we can easily access and change data. Stacks and Queues are the earliest data structure defined in computer science. A simple Python
list can act as a queue and stack as well. A queue follows FIFO rule (First In First Out) and used in programming for sorting. It is common for stacks and queues to be implemented with an array
or linked list.
Stack
A Stack is a data structure that follows the LIFO(Last In First Out) principle. To implement a stack, we need two simple operations:
push - It adds an element to the top of the stack.
pop - It removes an element from the top of the stack.
Operations:
Adding - It adds the items in the stack and increases the stack size. The addition takes place at the top of the stack.
Deletion - It consists of two conditions, first, if no element is present in the stack, then underflow occurs in the stack, and second, if a stack contains some elements, then the topmost element
gets removed. It reduces the stack size.
Traversing - It involves visiting each element of the stack.

Characteristics:
Insertion order of the stack is preserved.
Useful for parsing the operations.
Duplicacy is allowed.

x = ["Python", "C", "Android"]


[Link]("Java")
[Link]("C++")
print(x)
print([Link]())
print(x)
print([Link]())
print(x)

Queue
A Queue follows the First-in-First-Out (FIFO) principle. It is opened from both the ends hence we can easily add elements to the back
and can remove elements from the front.
To implement a queue, we need two simple operations:
enqueue - It adds an element to the end of the queue.
dequeue - It removes the element from the beginning of the queue.

Operations on Queue
Addition - It adds the element in a queue and takes place at the rear end, i.e., at the back of the queue.
Deletion - It consists of two conditions - If no element is present in the queue, Underflow occurs in the queue, or if a stack contains
some elements then element present at the front gets deleted.
Traversing - It involves to visit each element of the queue.

Characteristics
Insertion order of the queue is preserved.
Duplicacy is allowed.
Useful for parsing CPU task operations.
# Initializing a queue
queue = []

# Adding elements to the queue


[Link]('a')
[Link]('b')
[Link]('c')

print("Initial queue")
print(queue)

# Removing elements from the queue


print("\nElements dequeued from queue")
print([Link](0))
print([Link](0))
print([Link](0))

print("\nQueue after removing elements")


print(queue)

# Uncommenting print([Link](0))
# will raise and IndexError

Python JSON
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:
String
Number
Boolean
Null
Object
Array
JSON is built on the two structures:
It stores data in the name/value pairs. It is treated as an object, record, dictionary, hash table, keyed list.
The ordered list of values is treated as an array, vector, list, or sequence.
JSON data representation is similar to the Python dictionary. Below is an example of JSON data:
{
"book": [
{
"id": 01,
"language": "English",
"edition": "Second",
"author": "Derrick Mwiti"
],
{
{
"id": 02,
"language": "French",
"edition": "Third",
"author": "Vladimir"
}
}

Working with Python JSON


Python provides a module called json. Python supports standard library marshal and pickle module, and JSON API behaves similarly as these library.
Python natively supports JSON features.
The encoding of JSON data is called Serialization. Serialization is a technique where data transforms in the series of bytes and transmitted across the
network.
The deserialization is the reverse process of decoding the data that is converted into the JSON format.
This module includes many built-in functions.
import json
print(dir(json))

load()
loads()
dump()
dumps()

Serializing JSON
Serialization is the technique to convert the Python objects to JSON. Sometimes, computer need to process lots of information so it is good to store that
information into the file. We can store JSON data into file using JSON function. The json module provides the dump() and dumps() method that are
used to transform Python object.
thon objects are converted into the following JSON objects. The list is given below:

Sr. Python Objects JSON


1. Dict Object
2. list, tupleArray
3. Str String
4. int, float Number
5. True true
6. False false
7. None null

The dump() function


Writing JSON Data into File

Python provides a dump() function to transmit(encode) data in JSON format. It accepts two positional arguments, first
is the data object to be serialized and second is the file-like object to which the bytes needs to be written.

Import json
# Key:value mapping
student = {
"Name" : "Peter",
"Roll_no" : "0090014",
"Grade" : "A",
"Age": 20,
"Subject": ["Computer Graphics", "Discrete Mathematics", "Data Structure"]
}

with open("[Link]","w") as write_file:


[Link](student,write_file)

In the above program, we have opened a file named [Link] in writing mode. We opened this file in write mode
because if the file doesn't exist, it will be created. The [Link]() method transforms dictionary into JSON string.
The dumps () function
The dumps() function is used to store serialized data in the Python file. It accepts only one argument that is Python
data for serialization. The file-like argument is not used because we aren't not writing data to disk. Let's consider the
following example:
import json
# Key:value mapping
student = {
"Name" : "Peter",
"Roll_no" : "0090014",
"Grade" : "A",
"Age": 20
}
b = [Link](student)

print(b)

JSON supports primitive data types, such as strings and numbers, as well as nested list, tuples and objects.
import json

#Python list conversion to JSON Array


print([Link](['Welcome', "to", “waytocode"]))

#Python tuple conversion to JSON Array


print([Link](("Welcome", "to", “wytocode")))

# Python string conversion to JSON String


print([Link]("Hello"))

# Python int conversion to JSON Number


print([Link](1234))

# Python float conversion to JSON Number


print([Link](23.572))

# Boolean conversion to their respective values


print([Link](True))
print([Link](False))

# None value to null


print([Link](None))
Deserializing JSON
Deserialization is the process to decode the JSON data into the Python objects. The json module provides two methods load() and loads(), which are
used to convert JSON data in actual Python object form. The list is given below:

SR. JSON Python


1. Object dict
2. Array list
3. String str
4. number(int)int
5. true True
6. false False
7. null None
The above table shows the inverse of the serialized table but technically it is not a perfect conversion of the JSON data. It means that if we encode the
object and decode it again after sometime; we may not get the same object back.

Let's take real-life example, one person translates something into Chinese and another person translates back into English, and that may not be exactly
translated. Consider the simple example:
import json
a = (10,20,30,40,50,60,70)
print(type(a))
b = [Link](a)
print(type([Link](b)))

The load() function


The load() function is used to deserialize the JSON data to Python object from the file. Consider the following example:
import json
# Key:value mapping
student = {
"Name" : "Peter",
"Roll_no" : "0090014",
"Grade" : "A",
"Age": 20,
}

with open("[Link]","w") as write_file:


[Link](student,write_file)

with open("[Link]", "r") as read_file:


b = [Link](read_file)
print(b)

In the above program, we have encoded Python object in the file using dump() function. After that we read JSON file
using load() function, where we have passed read_file as an argument.
The json module also provides loads() function, which is used to convert JSON data to Python object. It is quite similar to
the load() function. Consider the following example:
Import json
a = ["Mathew","Peter",(10,32.9,80),{"Name" : "Tokyo"}]

# Python object into JSON


b = [Link](a)

# JSON into Python Object


c = [Link](b)
print(c)

[Link]() vs [Link]()
The [Link]() function is used to load JSON file, whereas [Link]() function is used to load string.
[Link]() vs [Link]()
The [Link]() function is used when we want to serialize the Python objects into JSON file and [Link]() function is used to
convert JSON data as a string for parsing and printing.

Python read csv file


CSV File
A csv stands for "comma separated values", which is defined as a simple file format that uses specific structuring to arrange tabular data. It stores tabular data such as
spreadsheet or database in plain text and has a common format for data interchange. A csv file opens into the excel sheet, and the rows and columns data define the standard
format.
Python CSV Module Functions
The CSV module work is used to handle the CSV files to read/write and get data from specified columns. There are different types of CSV functions, which are as follows:
csv.field_size_limit - It returns the current maximum field size allowed by the parser.
csv.get_dialect - It returns the dialect associated with a name.
csv.list_dialects - It returns the names of all registered dialects.
[Link] - It read the data from a csv file
csv.register_dialect - It associates dialect with a name. The name must be a string or a Unicode object.
[Link] - It writes the data to a csv file
o csv.unregister_dialect - It deletes the dialect which is associated with the name from the dialect registry. If a name is not a registered dialect name, then an error is being
raised.
csv.QUOTE_ALL - It instructs the writer objects to quote all fields. csv.QUOTE_MINIMAL - It instructs the writer objects to quote only those fields which contain special
characters such as quotechar, delimiter, etc.
csv.QUOTE_NONNUMERIC - It instructs the writer objects to quote all the non-numeric fields.
csv.QUOTE_NONE - It instructs the writer object never to quote the fields.
Reading CSV files
Python provides various functions to read csv file. We are describing few method of reading function.
Using [Link]() function
In Python, the [Link]() module is used to read the csv file. It takes each row of the file and makes a list of all the columns.
We have taken a txt file named as [Link] that have default delimiter comma(,) with the following data:
name,department,birthday month
Parker,Accounting,November
Smith,IT,October
Example
import csv
with open('[Link]') as csv_file:
csv_reader = [Link](csv_file, delimiter=',')
line_count = 0
for row in csv_reader:
if line_count == 0:
print(f'Column names are {", ".join(row)}')
line_count += 1

Read a CSV into a Dictionar


We can also use DictReader() function to read the csv file directly into a dictionary rather than deal with a list of individual string
elements.
Again, our input file, [Link] is as follows:
name,department,birthday month
Parker,Accounting,November
Smith,IT,October
Example
import csv
with open('[Link]', mode='r') as csv_file:
csv_reader = [Link](csv_file)
line_count = 0
for row in csv_reader:
if line_count == 0:
print(f'The Column names are as follows {", ".join(row)}')
line_count += 1
print(f'\t{row["name"]} works in the {row["department"]} department, and was born in {row["birthday month"]}.')
line_count += 1
print(f'Processed {line_count} lines.')
Python Write CSV File
CSV File
A CSV stands for "comma-separated values", which is defined as a simple file format that uses specific structuring to arrange tabular data. It
stores tabular data such as spreadsheet or database in plain text and has a standard format for data interchange. The CSV file opens into the
excel sheet, and the rows and columns data define the standard format.
Python CSV Module Functions
The CSV module work is to handle the CSV files to read/write and get data from specified columns. There are different types of CSV functions,
which are as follows:
csv.field_size_limit - It returns the current maximum field size allowed by the parser.
csv.get_dialect - Returns the dialect associated with a name.
csv.list_dialects - Returns the names of all registered dialects.
[Link] - Read the data from a CSV file
csv.register_dialect - It associates dialect with a name, and name must be a string or a Unicode object.
[Link] - Write the data to a CSV file
csv.unregister_dialect - It deletes the dialect, which is associated with the name from the dialect registry. If a name is not a registered dialect
name, then an error is being raised.
csv.QUOTE_ALL - It instructs the writer objects to quote all fields.
csv.QUOTE_MINIMAL - It instructs the writer objects to quote only those fields which contain special characters such as quotechar, delimiter,
etc.
csv.QUOTE_NONNUMERIC - It instructs the writer objects to quote all the non-numeric fields.
csv.QUOTE_NONE - It instructs the writer object never to quote the fields.
Writing CSV Files
We can also write any new and existing CSV files in Python by using the [Link]() module. It is similar to the [Link]() module and also
has two methods, i.e., writer function or the Dict Writer class.
It presents two functions, i.e., writerow() and writerows(). The writerow() function only write one row, and the writerows() function write
more than one row.
Dialects

It is defined as a construct that allows you to create, store, and re-use various formatting parameters. It supports several attributes; the most frequently used are:
[Link]: This attribute is used as the separating character between the fields. The default value is a comma (,).
[Link]: This attribute is used to quote fields that contain special characters.
[Link]: It is used to create new lines, and the default value is '\r\n'.
Let's write the following data to a CSV File.
data = [{'Rank': 'B', 'first_name': 'Parker', 'last_name': 'Brian'},
{'Rank': 'A', 'first_name': 'Smith', 'last_name': 'Rodriguez'},
{'Rank': 'C', 'first_name': 'Tom', 'last_name': 'smith'},
{'Rank': 'B', 'first_name': 'Jane', 'last_name': 'Oscar'},
{'Rank': 'A', 'first_name': 'Alex', 'last_name': 'Tim'}]
import csv

with open('[Link]', 'w') as csvfile:


fieldnames = ['first_name', 'last_name', 'Rank']
writer = [Link](csvfile, fieldnames=fieldnames)

[Link]()
[Link]({'Rank': 'B', 'first_name': 'Parker', 'last_name': 'Brian'})
[Link]({'Rank': 'A', 'first_name': 'Smith',
'last_name': 'Rodriguez'})
[Link]({'Rank': 'B', 'first_name': 'Jane', 'last_name': 'Oscar'})
[Link]({'Rank': 'B', 'first_name': 'Jane', 'last_name': 'Loive'})

print("Writing complete")
Python read excel file
Excel is a spreadsheet application which is developed by Microsoft. It is an easily accessible tool to organize, analyze, and store the
data in tables. It is widely used in many different applications all over the world. From Analysts to CEOs, various professionals use
Excel for both quick stats and serious data crunching.
Excel Documents
An Excel spreadsheet document is called a workbook which is saved in a file with .xlsx extension. The first row of the spreadsheet is
mainly reserved for the header, while the first column identifies the sampling unit. Each workbook can contain multiple sheets that are
also called a worksheets. A box at a particular column and row is called a cell, and each cell can include a number or text value. The
grid of cells with data forms a sheet.

Reading from an Excel file


First, you need to write a command to install the xlrd module.
pip install xlrd

Creating a Workbook
A workbook contains all the data in the excel file. You can create a new workbook from scratch, or you can easily create a workbook
from the excel file that already exists.

Code #1: Extract a specific cell


# Reading an excel file using Python
import xlrd

# Give the location of the file


loc = ("path of file")

# To open Workbook
wb = xlrd.open_workbook(loc)
sheet = wb.sheet_by_index(0)

# For row 0 and column 0


print(sheet.cell_value(0, 0))

Code #2: Extract the number of rows


# Program to extract number
# of rows using Python
import xlrd

# Give the location of the file


loc = ("path of file")

wb = xlrd.open_workbook(loc)
sheet = wb.sheet_by_index(0)
sheet.cell_value(0, 0)

# Extracting number of rows


print([Link])
Code #3: Extract the number of columns
import xlrd
loc = ("path of file")

wb = xlrd.open_workbook(loc)
sheet = wb.sheet_by_index(0)

# For row 0 and column 0


sheet.cell_value(0, 0)

# Extracting number of columns


print([Link])

Code #4 : Extracting all columns name


import xlrd

loc = ("path of file")

wb = xlrd.open_workbook(loc)
sheet = wb.sheet_by_index(0)

# For row 0 and column 0


sheet.cell_value(0, 0)

for i in range([Link]):
print(sheet.cell_value(0, i))

Code #5: Extract the first column

loc = ("path of file")

wb = xlrd.open_workbook(loc)
sheet = wb.sheet_by_index(0)
sheet.cell_value(0, 0)

for i in range([Link]):
print(sheet.cell_value(i, 0))
Code #6: Extract a particular row value

loc = ("path of file")

wb = xlrd.open_workbook(loc)
sheet = wb.sheet_by_index(0)

sheet.cell_value(0, 0)

print(sheet.row_values(1))
Python Write Excel File
The Python write excel file is used to perform the multiple operations on a spreadsheet using the xlwt module. It is an ideal way to write data and format
information to files with .xls extension.
If you want to write data to any file and don't want to go through the trouble of doing everything by yourself, then you can use a for loop to automate the
whole process a little bit.
Write Excel File Using xlsxwriter Module
We can also write the excel file using the xlsxwriter module. It is defined as a Python module for writing the files in the XLSX file format. It can also be
used to write text, numbers, and formulas to multiple worksheets. Also, it supports features such as charts, formatting, images, page setup, auto filters,
conditional formatting, and many others.
We need to use the following command to install xlsxwriter module:
Write Excel File Using openpyxl Module
It is defined as a package which is generally recommended if you want to read and write .xlsx, xlsm, xltx, and xltm files. You can check it by
running type(wb).
The load_workbook() function takes an argument and returns a workbook object, which represents the file. Make sure that you are in the same directory
where your spreadsheet is located. Otherwise, you will get an error while importing.
You can easily use a for loop with the help of the range() function to help you to print out the values of the rows that have values in column 2. If those
particular cells are empty, you will get None.
Writing data to Excel files with xlwt
You can use the xlwt package, apart from the XlsxWriter package to create the spreadsheets that contain your data. It is an alternative package for
writing data, formatting information, etc. and ideal for writing the data and format information to files with .xls extension. It can perform multiple
operations on the spreadsheet.
It supports features such as formatting, images, charts, page setup, auto filters, conditional formatting, and many others.
Pandas have excellent methods for reading all kinds of data from excel files. We can also import the results back to pandas.
Writing Files with pyexcel
You can easily export your arrays back to a spreadsheet by using the save_as() function and pass the array and name of the destination file to the
dest_file_name argument.
It allows us to specify the delimiter and add dest_delimiter argument. You can pass the symbol that you want to use as a delimiter in-between " ".

# import xlsxwriter module


import xlsxwriter

book = [Link]('[Link]')
sheet = book.add_sheet()

# Rows and columns are zero indexed.


row = 0
column = 0

content = ["Parker", "Smith", "John"]

# iterating through the content list


for item in content :

# write operation perform


[Link](row, column, item)

# incrementing the value of row by one with each iterations.


row += 1
[Link]()
Python Collection Module
The Python collection module is defined as a container that is used to store collections of data, for example - list, dict, set, and tuple, etc. It was introduced to improve the functionalities of the
built-in collection containers.
Python collection module was first introduced in its 2.4 release.

namedtuple()
The Python namedtuple() function returns a tuple-like object with names for each position in the tuple. It was used to eliminate the problem of remembering the index of each field of a tuple object
in ordinary tuples.

pranshu = ('James', 24, 'M')


print(pranshu)

import collections
d1=[Link]()
d1['A']=10
d1['C']=12
d1['B']=11
d1['D']=13

for k,v in [Link]():


print (k,v)

defaultdict()
The Python defaultdict() is defined as a dictionary-like object. It is a subclass of the built-in dict class. It provides all methods provided by dictionary but takes the first argument as a default data
type.
from collections import defaultdict
number = defaultdict(int)
number['one'] = 1
number['two'] = 2
print(number['three'])

Counter()
The Python Counter is a subclass of dictionary object which helps to count hashable objects.

from collections import Counter


c = Counter()
list = [1,2,3,4,5,7,8,5,9,6,10]
Counter(list)
Counter({1:5,2:4})
list = [1,2,4,7,5,1,6,7,6,9,1]
c = Counter(list)
print(c[1])

deque()
The Python deque() is a double-ended queue which allows us to add and remove elements from both the ends.

from collections import deque


list = ["x","y","z"]
deq = deque(list)
print(deq)

Chainmap Objects
A chainmap class is used to groups multiple dictionary together to create a single list. The linked dictionary stores in the list and it is public and can be accessed by the map attribute. Consider the following example.

from collections import ChainMap


baseline = {'Name': 'Peter', 'Age': '14'}
adjustments = {'Age': '14', 'Roll_no': '0012'}
print(list(ChainMap(adjustments, baseline)))
UserDict Objects
The UserDict behaves as a wrapper around the dictionary objects. The dictionary can be accessed as an attribute by using the UserDict object.
It provides the easiness to work with the dictionary.

It provides the following attribute.

data - A real dictionary used to store the contents of the UserDict class.

UserList Objects
The UserList behaves as a wrapper class around the list-objects. It is useful when we want to add new functionality to the lists. It provides the
easiness to work with the dictionary.

It provides the following attribute.

data - A real list is used to store the contents of the User class.

UserString Objects
The UserList behaves as a wrapper class around the list objects. The dictionary can be accessed as an attribute by using the UserString
object. It provides the easiness to work with the dictionary.

It provides the following attribute.

data - A real str object is used to store the contents of the UserString class.

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.

Class
Object
Method
Inheritance
Polymorphism
Data Abstraction
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
class ClassName:
<statement-1>
.
.
<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.

class car:
def __init__(self,modelname, year):
[Link] = modelname
[Link] = year
def display(self):
print([Link],[Link])

c1 = car("Toyota", 2016)
[Link]()

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 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.
Python Class and Objects
We have already discussed in previous tutorial, a class is a virtual entity and can be seen as a blueprint of an object. The class came into existence when it instantiated. Let's
understand it by an example.
Suppose a class is a prototype of a building. A building contains all the details about the floor, rooms, doors, windows, etc. we can make as many buildings as we want, based on
these details. Hence, the building can be seen as a class, and we can create as many objects of this class.
On the other hand, the object is the instance of a class. The process of creating an object can be called instantiation.
In this section of the tutorial, we will discuss creating classes and objects in Python. We will also discuss how a class attribute is accessed by using the object.
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
class ClassName:
#statement_suite
In Python, we must notice that each class is associated with a documentation string which can be accessed by using <class-name>.__doc__. A class contains a statement suite
including fields, constructor, function, etc. definition.
Consider the following example to create a class Employee which contains two fields as Employee id, and name.
The class also contains a function display(), which is used to display the information of the Employee.
class Employee:
id = 10
name = "Devansh"
def display (self):
print([Link],[Link])
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, usingself 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.
<object-name> = <class-name>(<arguments>)
class Employee:
id = 10
name = "John"
def display (self):
print("ID: %d \nName: %s"%([Link],[Link]))
# Creating a emp instance of Employee class
emp = Employee()
[Link]()
Delete the Object
We can delete the properties of the object or object itself by using the del keyword
class Employee:
id = 10
name = "John"

def display(self):
print("ID: %d \nName: %s" % ([Link], [Link]))
# Creating a emp instance of Employee class

emp = Employee()

# Deleting the property of object


del [Link]
# Deleting the object itself
del emp
[Link]()
It will through the Attribute error because we have deleted the object emp.

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.

Parameterized Constructor
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, 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.
class Employee:
def __init__(self, name, id):
[Link] = id
[Link] = name

def display(self):
print("ID: %d \nName: %s" % ([Link], [Link]))

emp1 = Employee("John", 101)


emp2 = Employee("David", 102)

# accessing display() method to print employee 1 information

[Link]()

# accessing display() method to print employee 2 information


[Link]()

Counting the number of objects of a class


The constructor is called automatically when we create the object of the class.
class Student:
count = 0
def __init__(self):
[Link] = [Link] + 1
s1=Student()
s2=Student()
s3=Student()
print("The number of students:",[Link])

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.
class Student:
# Constructor - non parameterized
def __init__(self):
print("This is non parametrized constructor")
def show(self,name):
print("Hello",name)
student = Student()
[Link]("John")
Python Parameterized Constructor

The parameterized constructor has multiple parameters along with the self.
Consider the following example.
class Student:
# Constructor - parameterized
def __init__(self, name):
print("This is parametrized constructor")
[Link] = name
def show(self):
print("Hello",[Link])
student = Student("John")
[Link]()

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.
class Student:
roll_num = 101
name = "Joseph"

def display(self):
print(self.roll_num,[Link])

st = Student()
[Link]()
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
class Student:
def __init__(self):
print("The First Constructor")
def __init__(self):
print("The second contructor")

st = Student()
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.

Python built-in class functions

The built-in functions defined in the class are described in the following table.

SN Function Description

1 getattr(obj,name,default) It is used to access the attribute of the object.

2 setattr(obj, name,value) It is used to set a particular value to the specific attribute of an object.

3 delattr(obj, name) It is used to delete a specific attribute.

4 hasattr(obj, name) It returns true if the object contains some specific attribute.

class Student:

def __init__(self, name, id, age):

[Link] = name

[Link] = id

[Link] = age

# creates the object of the class Student

s = Student("John", 101, 22)

# prints the attribute name of the object s

print(getattr(s, 'name'))

# reset the value of attribute age to 23

setattr(s, "age", 23)

# prints the modified value of age

print(getattr(s, 'age'))

# prints true if the student contains the attribute with name id

print(hasattr(s, 'id'))

# deletes the attribute age

delattr(s, 'age')

# this will give an error since the attribute age has been deleted

print([Link])
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
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.

class Student:
def __init__(self,name,id,age):
[Link] = name;
[Link] = id;
[Link] = age
def display_details(self):
print("Name:%s, ID:%d, age:%d"%([Link],[Link]))
s = Student("John",101,22)
print(s.__doc__)
print(s.__dict__)
print(s.__module__)

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 Inheritance
Syntax
class derived-class(base class):
<class-suite>
A class can inherit multiple classes by mentioning all of them inside the bracket. Consider the following syntax.

Syntax
class derive-class(<base class 1>, <base class 2>, ..... <base class n>):
<class - suite>

• class Animal:
• def speak(self):
• print("Animal Speaking")
• #child class Dog inherits the base class Animal
• class Dog(Animal):
• def bark(self):
• print("dog barking")
• d = Dog()
• [Link]()
• [Link]()
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 Inheritance

The syntax of multi-level inheritance is given below.

Syntax

class class1:

<class-suite>

class class2(class1):

<class suite>

class class3(class2):

<class suite>

Example

class Animal:

def speak(self):

print("Animal Speaking")

#The child class Dog inherits the base class Animal

class Dog(Animal):

def bark(self):

print("dog barking")

#The child class Dogchild inherits another child class Dog

class DogChild(Dog):

def eat(self):

print("Eating bread...")

d = DogChild()

[Link]()

[Link]()

[Link]()

Python Multiple inheritance

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

Python Inheritance

The syntax to perform multiple inheritance is given below.

Syntax

class Base1:

<class-suite>

class Base2:

<class-suite>

class BaseN:

<class-suite>

class Derived(Base1, Base2, ...... BaseN):

<class-suite>

Example

class Calculation1:

def Summation(self,a,b):

return a+b;

class Calculation2:

def Multiplication(self,a,b):

return a*b;

class Derived(Calculation1,Calculation2):

def Divide(self,a,b):

return a/b;

d = Derived()

print([Link](10,20))

print([Link](10,20))

print([Link](10,20))
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
class Animal:
def speak(self):
print("speaking")
class Dog(Animal):
def speak(self):
print("Barking")
d = Dog()
[Link]()

Real Life Example of method overriding


class Bank:
def getroi(self):
return 10;
class SBI(Bank):
def getroi(self):
return 7;

class ICICI(Bank):
def getroi(self):
return 8;
b1 = Bank()
b2 = SBI()
b3 = ICICI()
print("Bank Rate of interest:",[Link]());
print("SBI Rate of interest:",[Link]());
print("ICICI Rate of interest:",[Link]());
Data abstraction in python
Abstraction is an important aspect of object-oriented programming. In python, we can also perform data hiding by
adding the double underscore (___) as a prefix to the attribute which is to be hidden. After this, the attribute will not be
visible outside of the class through the object.

Consider the following example.

Example
class Employee:
__count = 0;
def __init__(self):
Employee.__count = Employee.__count+1
def display(self):
print("The number of employees",Employee.__count)
emp = Employee()
emp2 = Employee()
try:
print(emp.__count)
finally:
[Link]()

You might also like