Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
2 views

PYTHONPROGRAMMING_UNIT1

Python is a versatile, high-level programming language known for its simplicity and ease of learning, making it suitable for various applications including web development, machine learning, and desktop applications. The name 'Python' was inspired by the BBC comedy series 'Monty Python's Flying Circus', and the language supports multiple programming paradigms such as object-oriented and functional programming. Python has evolved through several versions, with Python 3.x being the current standard, and it offers a range of IDEs and libraries for developers.

Uploaded by

prashobh1719
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

PYTHONPROGRAMMING_UNIT1

Python is a versatile, high-level programming language known for its simplicity and ease of learning, making it suitable for various applications including web development, machine learning, and desktop applications. The name 'Python' was inspired by the BBC comedy series 'Monty Python's Flying Circus', and the language supports multiple programming paradigms such as object-oriented and functional programming. Python has evolved through several versions, with Python 3.x being the current standard, and it offers a range of IDEs and libraries for developers.

Uploaded by

prashobh1719
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 54

1|Page

PYTHON programming

 Python is a general purpose, dynamic, high-level, and interpreted

programming language.
 It is simple and easy to learn and provides lots of high-level data structures.

 Python is not intended to work in a particular area, such as web

development that is why it is known as multipurpose programming


language.
 Python makes the development and debugging fast because

there is no compilation step included in Python

Why the Name Python?


 There is a fact behind choosing the name Python
 Guido van Rossum was reading the script of a popular BBC comedy series
"Monty Python's Flying Circus". It was late on-air 1970s.
 Van Rossum wanted to select a name which unique, short and little-bit
mysterious. So he decided to select naming python after the "Monty
Python's Flying Circus" for their newly created programming language.
 Python is also versatile and widely used in every technical field such as
Machine learning, Artificial intelligence, Web development, Mobile
Application and Desktop Application..etc

Features of Python:-
Open Source:- There is no need to pay for Python software. It can be free
downloaded from www.python.org website.
Portable:- Due to its open-source nature, Python has been ported to many
platforms. Python programs can work on any platforms without any
modification.
Easy to Learn and Use :- Python is easy to learn as compared to other
programming languages. Its syntax is straight forward and much the same as
Python programming Bhavani M
2|Page

the English language. There is no use of the semicolon or curly-bracket, the


indentation defines the code block.
Expressive Language :- Python can perform complex tasks using a few
lines of code. A simple example, the hello world program you simply type
print("Hello World"). It will take only one line to execute, while Java or C
takes multiple lines.
Interpreted Language:- Python is an interpreted language it means the
Python program is executed one line at a time. The advantage of being
interpreted language, it makes debugging easy.
Cross-platform Language:- Python can run equally on different platforms
such as Windows, Linux, UNIX, and Macintosh, etc. So, we can say that
Python is a portable language. It enables programmers to develop the
software for several competing platforms by writing a program only once.
Object-Oriented Language :- Python supports object-oriented language
and concepts of classes and objects come into existence. It supports
inheritance, polymorphism, and encapsulation, etc.
Large Standard Library:- It provides a vast range of libraries for the
various fields such as machine learning, web developer, and also for the
scripting. There are various machine learning libraries such as Pandas,
Numpy, Keras, and Pytorch, etc.
Django, flask, pyramids are the popular framework for Python web
development.
GUI Programming Support:- Graphical User Interface is used for the
developing Desktop application. PyQT5, Tkinter, Kivy are the libraries
which are used for developing the web application.
Integrated :-It can be easily integrated with languages like C, C++, and
JAVA..etc.
Dynamic Memory Allocation:- In Python, we don't need to specify the
data-type of the variable. When we assign some value to the variable, it

Python programming Bhavani M


3|Page

automatically allocates the memory to the variable at run time. Suppose we


are assigned integer value 15 to x, then we don't need to write int x = 15. Just
write x = 15.

Python Applications

Python is known for its general-purpose nature that makes it applicable


in almost every domain of software development. Python makes its
presence in every emerging field. It is the fastest- growing
programming language and can develop any application.

Web Applications:- We can use Python to develop web


applications. It provides libraries to handle internet protocols such
as HTML and XML, JSON, Email processing. One of Python web-
framework named Django is used. Python provides many useful
frameworks, and these are given below:
• Django and Pyramid framework(Use for heavy applications)

• Flask and Bottle (Micro-framework)

Desktop GUI Applications:- The GUI stands for the Graphical User
Interface, which provides a smooth interaction to any application.
Python provides a Tk GUI library to develop a user interface. Some
popular GUI libraries are Tkinter or Tk , wxWidgetM , Kivy (used for
writing multitouch applications )

Console-based Application:- Console-based applications run from


the command-line or shell. These applications are computer program
which are used commands to execute. This kind of application was
more popular in the old generation of computers.

PYTHON VERSIONS
Python is a high-level programming language known for its simplicity

Python programming Bhavani M


4|Page

and readability.
Over the years several versions of python have been released each
introducing new features and improvements.
Here are some key points about different Python versions
Python 2.x:
Python 2.x was the original major version of Python and was released in the
year 2000.
Python 2.7, released in 2010, is the last version of Python 2 and is still used
in some legacy systems.
Python 2.x has reached its end-of-life status, and no new features or bug
fixes are being released for it. It is strongly recommended to migrate to
Python 3.
Python 3.x:

Python 3.x introduced significant changes and improvements over Python


2.x. It aimed to address various design flaws and inconsistencies.
Python 3.0, released in 2008, was not backward-compatible with Python
2.x due to the introduction of some breaking changes.
The adoption of Python 3 was initially slow, but it has become the
standard for new projects and is widely used today.
Each Python 3.x release introduces new features, performance
enhancements, and bug fixes.
Python 3.4 (2014): Introduced the asyncio module for asynchronous I/O
programming.
Python 3.5 (2015): Introduced the "async" and "await" keywords for
native coroutine support.
Python 3.6 (2016): Added features like f-strings for formatted string
literals and introduced the "typing" module for type hints.
Python 3.7 (2018): Included various improvements such as the "data
classes" module and the "breakpoint ()" function.
Python programming Bhavani M
5|Page

Python 3.8 (2019): Introduced the "walrus operator" (:=) for assignment
expressions and added the "math. Prod()" function.
Python 3.9 (2020): Brought features like dictionary merging (| operator)
and improved support for type annotations.
Note: Beyond September 2021, several more Python versions have been
released, including Python 3.10 in October 2021 and subsequent updates.

PYTHON INSTALLATION

Visit the official Python website: Go to the official Python website at


https://www.python.org/. This website provides downloads for the latest stable
release of Python.
Choose the appropriate version: Python offers different versions for
different operating systems. Make sure to select the version that corresponds
to your operating system. For most users, the recommended version is the
latest stable release of Python 3.x.
Download the installer: Once you've selected the appropriate version, click
on the download link to get the installer file. The website should
automatically detect your operating system and provide the relevant
download options.
Run the installer: Locate the downloaded installer file and run it. The
installer will guide you through the installation process. Make sure to check
the box that says "Add Python to PATH" during the installation. This will
make it easier to run Python from the command line.
Verify the installation: After the installation is complete, you can verify if
Python is installed correctly. Open a command prompt (on Windows) or a
terminal (on macOS or Linux) and type python version or python3 version
and press Enter. This will display the installed Python version. If the version
number is displayed, it means Python is installed successfully.Additionally,
you may consider installing a package manager called pip if it's not already
Python programming Bhavani M
6|Page

included with your Python installation. Pip allows you to easily install and
manage additional Python libraries.

To install pip, follow these steps:

 Download the get-pip.py script: Go to https://bootstrap.pypa.io/get-


pip.py and download the get-pip.py script to your computer.
 Run the script: Open a command prompt or terminal, navigate to the
directory where you downloaded the script, and run the following
command:

python get-pip.py

 Verify the installation: After the installation is complete, you can verify
if pip is installed correctly by running the following command:

pip --version

 If the version number is displayed, it means pip is installed successfully.


You can now start writing and running Python programs

PYTHON COMMAND LINE MODE


Python provides an interactive command line mode called the Python
Interactive Shell. It allows you to execute Python code statements and see the
results immediately.

To access the Python command line mode, you can follow these steps:
Open your terminal or command prompt.
Type python or python3 (depending on your Python installation) and press
Enter.
This will start the Python interpreter and display the Python version and a
prompt >>>.
Now, you can start typing Python statements and press Enter to execute them.
The interpreter will immediately evaluate the statement and display the result (if
any).
Python programming Bhavani M
7|Page

You can continue entering statements one by one, and the interpreter will
execute them sequentially.
To exit the Python command line mode, you can type exit() or quit() and press
Enter. This will exit the interpreter and return you to the terminal.

>>> print("Hello, World!")

Hello, World!
>>> x = 10
>>> y = 5
>>> x + y
15
>>> exit()
In this example, we start the Python interpreter by typing python in the
terminal.
We then enter various Python statements, such as printing a string, assigning
values to variables (x and y), and performing arithmetic operations. The
interpreter evaluates the statements and displays the results.
Finally, we exit the Python command line mode by typing exit(), and the
prompt returns to the terminal.

PYTHON IDE’S
There are several popular Integrated Development Environments (IDEs) available
for Python programming.

Here are some of the commonly used ones:

Python programming Bhavani M


8|Page

PyCharm: Developed by JetBrains, PyCharm is a powerful and rich feature IDE for
Python. It offers a wide range of tools for code editing, debugging, testing, and version
control integration. PyCharm is available in both a free Community edition and a paid
Professional edition.
Visual Studio Code (VS Code): VS Code is a highly popular and extensible code editor
that provides excellent support for Python. It offers a wide range of extensions that can be
installed to enhance Python development. VS Code is free and available for Windows,
macOS, and Linux.
Anaconda: Anaconda is a Python distribution that comes with its own IDE called
Anaconda Navigator. It is focused on data science and scientific computing, providing
accurate collection of Python packages for these domains. Anaconda is available for free
and supports multiple platforms.
Spyder: Spyder is another IDE specifically designed for scientific computing and data
analysis with Python. It offers an interactive development environment with features like
code introspection, debugging, and variable exploration. Spyder is open-source and can be
installed using Anaconda or directly via pip.
Jupyter Notebook/Jupyter Lab: Jupyter Notebook is a web-based interactive
environment that allows you to create and share documents containing live code,
visualizations, and explanatory text. Jupyter Lab is the next-generation UI for Jupyter
Notebook, offering a more versatile and extensible interface. Both Jupyter Notebook and
Jupyter Lab are widely used for data analysis, research, and prototyping.

SIMPLE PYTHON PROGRAM

num1 = float(input("Enter the first number: "))

num2 = float(input("Enter the second number: "))

# Add the numbers

result = num1 + num2


Python programming Bhavani M
9|Page

# Print the result


print("The sum is:", result)
In this program, the user is prompted to enter two numbers.

The input() function is used to read the user's input.

float() is used to convert the input into floating-point numbers (allowing for
decimal values).

The program then adds the two numbers together and stores the result in the
result variable.

Finally, the program uses the print() function to display the result on the
console, along with an informative message.

PYTHON BASICS

Identifiers

Identifier is the name given to various program elements like variables, function,
arrays, classes, strings etc.

The Python identifiers follow the following rules:

 The Name should begin with an alphabet.

 Only alphabets, digits and underscores are permitted.

 Distinguish between uppercase and lowercase alphabets.

 Keywords should not be used as identifiers.

 No blank space between the identifiers.

Keywords

 The keywords are also called as reserved word. The keywords have predefined
meaning.

 All keywords are written in lower case alphabets.


Python programming Bhavani M
10 | P a g e

 The Python keywords are:


and del for lambda true
as elif from not try
assert else global or while
break except if pass with
class exec import print Yield
continue false in raise

Statement and Expression


Statement:
Any Instruction that a python interpreter can execute (carry out) is called a
Statement.
A Statement is the smallest executable unit of code that has an effect, like creating
a variable or displaying a value.
Each and every line of code that we write in any programming language is called a
statement. Because, all the lines are executable by the interpreter or the compiler of
that programming language.
Example:

X=3;
Print(x)

Expression
An expression is a combination of operators and operands that is interpreted to
produce some other value.

An expression is evaluated as per the precedence of its operators. So that if


there is more than one operator in an expression, their precedence decides
which operation will be performed first.

We have many different types of expressions in Python. Arithmetic,


Relational, Logical and Assignment.

Python programming Bhavani M


11 | P a g e

Variables

A variable is the name given to a memory location.


A value holding Python variable is also known as an identifier.
Variable names must begin with a letter or an underscore, but they can be a group of both
letters and digits.
The name of the variable should be written in lowercase. Both Rahul and rahul are distinct
variables.
Declaring Variable and Assigning Values
In Python, we don't have to explicitly declare variables. The variable is declared
automatically whenever a value is added to it.
The equal (=) operator is utilized to assign worth to a variable.
Example
A=5 (A is the variable 5 is the value)

Operator

Operators are special symbols that perform operations on variables and values.

Arithmetic Operators: Arithmetic operators are used to perform mathematical


operations like addition, subtraction, multiplication etc.

Symbol Description Example-1


+ Addition >>> 5 + 6
11
- Subtraction >>>10-5
5
* Multiplication >>> 5*6
30
/ Division >>> 10 / 5
2
% Remainder / Modulo >>> 5 % 2
1

Python programming Bhavani M


12 | P a g e

** Exponentiation >>> 2**3


8
// Integer Division >>> 7.0 // 2
3.0

Relation al Operators: Relational operators are used to compare two values

Symbol Description Example-1


< Less than >>> 7<10
True
> Greater Than >>> 7 >10
False
<= Less than or equal to >>> 7<=10
True
>= Greater than or equal >>> 7>=10
to False
!= , <> Not equal to >>> 7!=10
True
== Equal to >>> 7==10
False

Logical Operators : Logical operators are used to combine conditional statements

Symbol Description Example


or If any one of the operand is true, >>> 7<=10 or 7
then condition becomes ==10
TRUE True
and If both the operands are true, then >>>7<10 and 7 >20
the condition becomes False
TRUE
not Reverse the state of operand / >>> not
condition 7<10
False
Python programming Bhavani M
13 | P a g e

Assignment Operator: Assignment operators are used to assign values to the variables.

Symbol Description Example-


1
= Assigned values from right side >>> x=10
operands to left variable.
10

Bitwise Operator: a bit is the smallest unit of data storage and it can have only
one of the two values i.e 0 and 1. Bitwise operators works on bits and perform bit
by bit operation.

Symbol Description Example


| Performs binary OR operation 5 | 3 gives 7
& Performs binary AND operation 5 & 3 gives 1
^ Performs binary one's complement ~5 gives -6
operation
<< Left shift operator: The left-hand side operand 0010 << 2 gives
bit is moved left by the number specified on the 8
right handside (Multiply by 2)
>> Left shift operator: The left-hand side 100 << 2 gives 1
operand bit is moved left by the number
specified on the right-hand side (Divided by 2)

Membership operators: Python has membership operators which test for


membership in a sequence such as strings, lists or tuples. There are two
membership operators are:
Symbol Description Example
in Returns True if the specified operand is >>> x = [1,2,4,6,8]
found in the sequence >>>3 in x
False
Not in Returns True if the specified operand is not >>> x = [1,2,4,6,8]
found in the sequence >>> 3 not in x
True

Python programming Bhavani M


14 | P a g e

Identity operator: Identity operators compare the memory locations of


two objects. There are two Identity operators are
Symbol Description Example
Is Returns True if two variables point >>>X=10
to the same object and False, >>>Y=10
>>> X is Y
otherwise
true

is not Returns False if two variables point >>>X=10


to the same object and True, >>>Y=10
otherwise >>> X is not Y
false

Precedence and Associativity of Operators:

Operator Precedence: - This is used in an expression with more than one operator with
different precedence to determine which operation to perform first. Operator precedence
affects how an expression is evaluated.

Operator Associativity: -If an expression contains two or more operators with the
same precedence, then Operator Associativity is used to determine. It can either be Left
to Right or from Right to Left.

Example: “*” and “/” have the same precedence and their associativity is Left to Right,
so the expression “100 / 10 * 10” is treated as “(100 / 10) * 10”.

Operator Descripti Associativity


on
() Parentheses left-to-right

** Exponent right-to-left

*/% Multiplication/division/modulus left-to-right

Python programming Bhavani M


15 | P a g e

+– Addition/subtraction left-to-right

<< >> Bitwise shift left, Bitwise shift right left-to-right

< <= Relational less than/less than or equal to left-to-right


Relational greater than/greater than or equal
> >=
to

== != Relational is equal to/is not equal to left-to-right

is, Identity
isnot left-to-right
Membership operators
in,
notin

& Bitwise AND left-to-right

^ Bitwise exclusive OR left-to-right

| Bitwise inclusive OR left-to-right

not Logical NOT right-to-left

and Logical AND left-to-right

or Logical OR left-to-right

= Assignment right-to-left

Python programming Bhavani M


16 | P a g e

Example: x = 7 + 3 * 2;

here, x is assigned 13, not 20 because operator * has higher precedence than +, so it first
multiplies 3*2 and then adds into 7.

Data Types
A data type represents the type of data stored into a variable or memory. There
are 5 different data types are:
 None type
 Numeric type
 Sequences
 Sets
 Dictionary

None data type:-


The none data type represents an object that does not contain any value.
In java language it is called “NULL” object. But in Python it is called
as “none”. In Python maximum of only one none object is provided.
If no value is passed to the function, then the default value will be taken as „none‟.

Numeric data type:


The numeric type represents numbers. There are 3 subtypes:
 int
 float
 complex
int data type: The int data type represents integer number (Whole number). An
integer number is number without fraction.
E.g. a=10 b=-29
float data type: The float data type represents floating point number.
Python programming Bhavani M
17 | P a g e

A floating point number is a number with fraction.


complex data type: A complex number is number is written in the form of x +yj.
Here x is the real part and y is the imaginary part.
Sequences: A sequence represents a group of items or elements.
Important sequences as follows
 str
 list
 tuple

str data type :


The str represents string data type.
A string is a collection of character enclosed in single or double quotes.
Both are valid.
E.g: str=”kiran” # str is name of string
 Triple double quote or triple single quotes are used to embed a string in
another string (Nested string).
 The [] operator used to retrieve specified character from the string.
 The string index starts from 0.
 Hence, str [0] indicates the 0th character in the string.
str=” Turnaround”
print(str) # it displays -Tu r n a r o u n d
list data type:
A List is a collection which is ordered and changeable.
It allows duplicate members.

A list is similar to array.


Lists are represented by square brackets [ ] and the elements are
separated by comma.
The main difference between a list and an array is that a list can store

Python programming Bhavani M


18 | P a g e

different data type elements, but an array can store only one type of
elements.
List can grow dynamically in memory but the size of array is fixed
and they cannot grow dynamically.
Example: list=[10,3.5,-20, “evening ”+‟Saturday”] # create a list
print(list) #it display all elements in the list
10,3.5,-20,evening,Saturday
Tuple data type:
A tuple is similar to list.
A tuple contains group of elements which can be different types.
The elements in the tuple are separated by commas and enclosed in parentheses ().
The only difference is that tuples are immutable. Tuples once created cannot be
modified.
The tuple cannot change dynamically.

e.g. tpl=(10,3.5,-20, “evening”+‟Saturday”) # create a tuple


print(tpl) #it display all elements in the tuple:
10,3.5,-20,evening,Saturday
Sets:

Set is an unordered collection of unique items and un-indexed.


The order of elements is not maintained in the sets.
A set does not accept duplicate elements.
Set is defined by values separated by comma inside braces { }.
To create a set, we should enter the elements separated by comma inside a curly brace.
e.g. s = {10,30, 5, 30,50}
print(s)# it display :
{10,5,30,50}

Python programming Bhavani M


19 | P a g e

In the above example, it displays un-orderly and repeated elements only


once, because set is unordered collection and unique items.

We can use set() to create a set as K=set(“kvn”)

Print(K) # it display : “kvn”

Dictionary:

A dictionary is an unordered collection, changeable and indexed.

In Python dictionaries are written with curly brackets, and they have keys and values.

That means dictionary contains pair of elements such that first element
represents the key and the next one becomes its value.
The key and value should be separated by a colon(:) and every pair should
be separated by comma.
All the elements should be enclosed inside curly brackets.

e.g. d={3: “ssc”+ 4:‟tarun”+ 5:‟kvc”+ 6: “vedish”}

Here, d is the name of dictionary. 3 is the key and its associated value is “ssc”.
The next is 4 and its value is “tarun” and so on.
Print(d) # it displays :
{3: “ssc”+ 4: “tarun”+ 5:‟kvc”+ 6: “vedish”}
Print(d[5]) # it display : kvc

Indentation

whitespace at the beginning of the line is called indentation.


Example 1:-

if 5 > 2:

print("Five is greater than two!")


Python programming Bhavani M
20 | P a g e

Example 2:- Python will give you an error if you skip the indentation

if 5 > 2:

print("Five is greater than two!")

Comment:

Comments are non-executable statements.


It means compiler will not execute them.
Comments are any text to the right of the # symbol and is mainly useful as notes for
the reader of the program.
There are two types of comments in Python, Single line comments and Multiline
comments

Single line Comments:


this comment starts with a hash symbol (#) and are useful to mention that the
entire line till the end should be treated as comments.
Eg: k=5 # assign 5 to variable k
In the above example, first line starts with # and hence the total line treated
as comments.

Multi line Comments:

The triple double quotes („‟ ”‟) or triple single quotes (“““ ”””) are called
multi line comments.

They are used to enclose a block of lines as comments.

Eg: “““This is illustrated as

multi line comments. ”””

Built-in-functions:-Input and Output

Python programming Bhavani M


21 | P a g e

 The purpose of a computer is to process data and return results.


 It means that we should provide data to the computer. The data given to the

computer is called input. The results returned by the computer are called
output. So, we can say that a computer takes input, processes that input and
produces the output.
 To provide input to a computer, Python provides some statements which are

called Input statements. Similarly, to display the output, there are Output
statements available in Python.

Output statements
 To display output or results, Python provides the print() function.
 This function can be used in different formats.

print() Statement :-When the print() function is called simply, it will throw
the cursor to the next line. It means that a blank line will be displayed.

The print(formatted string) Statement :-The output displayed by the print()


function can be formatted as we like. The special operator “%” (percent) can be
used for this purpose. It joins a string with a variable or value in the following
format:

print (“formatted string”% (variables list))

In the “formatted string”, we can use %i or %d to represent decimal integer numbers. We


can use %f to represent float values. Similarly, we can use %s to represent strings. See the
example below:
x=10

print('value=‟%i%x)

value= 10

As seen above, to display a single variable (i.e. x), we need not wrap it inside parentheses.
Python programming Bhavani M
22 | P a g e

Input Statements

To accept input from keyboard, Python provides the input () function. This
function takes a value from the keyboard and returns it as a string.

For example
str = input('Enter your name:')
Enter your name: Raj

print(str)

output: Raj

Type conversion in python

Type conversion refers to changing a given object from one data type to another data
type.
Type conversion in Python is used to convert values from one data type to another,
either automatically by the Python interpreter or manually by the programmer using
in- built functions.
Note that not all data types can be converted into each other. For example, there's no
way a string consisting of English letter alphabets can be converted into an integer.
Implicit Type Conversion

Implicit type conversion is when the Python interpreter converts an object from one
data type to another on its own without the need for the programmer to do it
manually.
The smaller data type is covered into higher data type to prevent any loss of data
during the runtime. Since the conversion is automatic, we do not require to use any
function explicitly in the code.
Example:
english, science, maths, sst, it = 95, 92, 97, 90, 98
Python programming Bhavani M
23 | P a g e

total = english + science + maths + sst + it


print("Total marks:", total, "is of type", type(total))
percentage = total / 5
print("Percentage:", percentage, "is of type", type(percentage))
Output:
Total marks: 472 is of type <class 'int'>
Percentage: 94.4 is of type <class 'float'>

Explicit Type Conversion


Suppose we need to convert a value from a higher to a lower data type. Implicit type
conversion cannot be used here.
Explicit type conversion means that the programmer manually changes the data type
of an object to another with the help of in-built Python functions like str () for
converting to string type and int () for converting to the integer type.
Note: In explicit type conversion, loss of data may occur as we enforce a given
value to a lower data type. For example, converting a float value to int will round off
the decimal places in the output.
Example:
Conversion from string to list
Value=”hello” Print(value)
Value1=list(value)
Print(value1)
Output Value:hello
Value1:[„h,e,l,l,o]

PYTHON LIBRARY
A Python library is a collection of related modules.
It contains bundles of code that can be used repeatedly in different programs.
It makes Python Programming simpler and convenient for the programmer. As we don‟t
need to write the same code again and again for different programs.
Modules on the other hand refer to any python file saved with the .py extension.

Python programming Bhavani M


24 | P a g e

Modules often contain code such as functions, classes and statements that can be
imported and used within other programs.
Python libraries are pre-written sets of code that provide various functionalities to
developers.
These libraries contain modules and packages that can be imported into your python
programs to extend their capabilities.
Python libraries are created and maintained by the Python community and cover a wide
range of areas, including data analysis, web development, machine learning, scientific
computing, and more.

To import a library in Python, you can use the import statement. Here are the
steps to import a library:

 Identify the library: Determine the name of the library you want to import.
Libraries in Python often come with built-in functionality or provide additional
features for specific purposes.
 Import the library: Use the import statement followed by the name of the
library. You can place the import statement at the beginning of your Python script
or module.
 Utilize the library's features: Once the library is imported, you can access its
functions, classes, or other elements using the library's name followed by a dot (.)
notation.
Examples for library

Matplotlib: This library is responsible for plotting numerical data. And that‟s why
it is used in data analysis. It is also an open-source library and plots high-defined
figures like pie charts, histograms, scatterplots, graphs, etc.
Pandas: It is an open-source machine learning library that provides flexible high-
level data structures and a variety of analysis tools. It eases data analysis, data
manipulation, and cleaning of data. Pandas support operations like Sorting, Re-

Python programming Bhavani M


25 | P a g e

indexing, Iteration, concatenation, Conversion of data, Visualizations,


Aggregations, etc.
Numpy: The name “Numpy” stands for “Numerical Python”. It is the
commonly used library. It is a popular machine learning library that supports large
matrices and multi-dimensional data. It consists of in-built mathematical functions
for easy computations..
SciPy: The name SciPy stands for “Scientific Python”. It is an open- source
library used for high-level scientific computations. This library is built over an
extension of Numpy. It works with Numpy to handle complex computations.
While Numpy allows sorting and indexing of array data, the numerical data code
is stored in SciPy.
Scrapy: It is an open-source library that is used for extracting data from websites.
It provides very fast web crawling and high-level screen scraping. It can also be
used for data mining and automated testing of data.
PyGame: This library provides an easy interface to the Standard Directmedia
Library (SDL) platform-independent graphics, audio, and input libraries. It is
used for developing video games using computer graphics and audio libraries
along with Python programming language.

Here's an example that demonstrates the steps to import and use the math library,
which provides various mathematical functions:
Step 1: Identify the library
# The math library provides mathematical functions

Step 2: Import the library


import math
Step 3: Utilize the library's features
# Calculate the square root of a number
Python programming Bhavani M
26 | P a g e

num = 16
sqrt = math.sqrt(num)
print("The square root of", num, "is", sqrt) #
Calculate the value of pi
pi = math.pi
print("The value of pi is", pi)

In this example, the math library is imported using the import statement. After
importing, we can access the library's functions and constants using the math.
prefix.
We calculate the square root of a number (math.sqrt()) and assign it to the
variable sqrt. We then print the result. Additionally, we access the value of pi
(math.pi) and print it.
By importing the math library, we gain access to its features and can use them in
our program.

Python Control Flow

Control Flow Statements


The flow control statements are divided into three categories
Conditional statements
Iterative statements.
Transfer statements

Conditional statements
In Python, condition statements act depending on whether a given condition is true
or false.
Condition statements always evaluate either True or False.
If the condition is True, then the True block of code will be executed, and if the
Python programming Bhavani M
27 | P a g e

condition is False, then the block of code is skipped, and the controller moves to the
next line
We can call these conditional statements as decision making statements because
they are used to make decision based on given condition

There are four types of conditional statements.


if statement
if-else
elif
nested if-else

If statement :
In control statements, The if statement is the simplest form. It takes a condition and
evaluates to either True or False.
If the condition is True, then the True block of code will be executed, and if the
condition is False, then the block of code is skipped, and The controller moves to the
next line

Syntax for the if statement


if condition:
statement 1
statement 2
:
statement n

Example-1
a=6
b = 10
if a < b:
print (“a is less than b”)

Python programming Bhavani M


28 | P a g e

output:
a is less than b

Example-2
a = int (input (“enter no:”))
if a < 10:
print (“a value is less than 10”)
output:
enter no:6
a value is less than 10

If – else statement:
The if-else statement checks the condition and executes the if block of code when the condition
is True, and if the condition is False, it will execute the else block of code.
Syntax for if-else statement
if condition:
statement 1
else:
statement 2
If the condition is True, then statement 1 will be executed If the condition is False, statement 2
will be executed

Example-1
a=int (input (“enter a value:”))
b = int (input (“enter b value:”))
if a < b:
print (“a is smaller no”)
else:
print(“b is smaller no ”)

output 1:
enter a value :2
Python programming Bhavani M
29 | P a g e

enter b value :30


a is smaller no

Example2:
password = input ('Enter password ')
if password == "nisha123":
print("Correct password")
else:
print("Incorrect Password")

Chain multiple if statement in Python (elif statement):


The elif statement checks multiple conditions one by one and if the condition fulfills,
then executes that code.
In this variant of „if statement‟, there are many else if conditions declared.
If the first condition does not satisfy then the next condition is executed. But if this
condition also does not satisfy then the next condition is executed.
Syntax for elif statement:
if condition-1:
statement 1
elif condition-2:
statement 2
elif condition-3:
statement 3
else:
statement
Note – elif is short for else if. If the condition for if is FALSE then the elif condition is
checked and executed if found TRUE or, the statements after elif are executed.
Example
a = int (input('Enter number : '))
Python programming Bhavani M
30 | P a g e

if (a<20):
print (“a value is less than 20”)
elif (a==30):
print (“a value is equal to 30”)
elif (a==40):
print (“a value is equal to 40”)
else:
print(“number not found”)
output:
Enter number : 9
a value is less than 20
Enter number : 30
a value is equal to 3

Nested if-else statement


In Python, the nested if-else statement is an if statement inside another if- else
statement.
It is allowed in Python to put any number of if statements in another if statement.
Indentation is the only way to differentiate the level of nesting. The nested if-else is
useful when we want to make a series of decisions.

Syntax of the nested-if-else:


if conditon_outer:
if condition_inner:
statement of inner if
else:
statement of inner else
else:
statement outside if block
Python programming Bhavani M
31 | P a g e

Example: Find a greater number between two numbers


num1 = int(input('Enter first number '))
num2 = int(input('Enter second number '))
if num1 >= num2:
if num1 == num2:
print(num1, 'and', num2, 'are equal')
else:
print(num1, 'is greater than', num2)
else:
print(num1, 'is smaller than', num2)
Output 1:
Enter first number 56
Enter second number 15
56 is greater than 15

Output 2:
Enter first number 29
Enter second number 78
29 is smaller than 78

Python Iterative Statements

Iteration statements or loop statements allow us to execute a block of statements as


long as the condition is true.
Loops statements are used when we need to run same code again and again, each
time with a different value.

Type of Iteration Statements

Python programming Bhavani M


32 | P a g e

While Loop
For Loop
Nested For Loops
While Loop In Python

While Loop in Python is used to execute a block of statement as long as a given


condition is true. And when the condition is false, the control will come out of the
loop.
The condition is checked every time at the beginning of the loop.

While Loop Syntax


while (condition):
statements

Example Of While Loop


x=0
while (x < 5):
print(x)
x=x+1
Output :-
0
1
2
3
4

using else statement with while loops


As discussed above, while loop executes the block until a condition is satisfied. When
the condition becomes false, the statement immediately after the loop is executed.
The else clause is only executed when your while condition becomes false. If you break
out of the loop, or if an exception is raised, it won‟t be executed.

Python program Using else statement with while loop :


Password =” 123456”

Python programming Bhavani M


33 | P a g e

Input_password=input(“enter password:”)
while password != input_password:
Input_password=input(“enter password:”)
else:
print(“unlocked!!!!!!!!!”)

output:
enter password:11111
enter password:135656
enter password:123456
unlocked!!!!!!!!!

For Loop In Python


For loop in Python is used to iterate over items of any sequence, such as a list or a string.

For Loop Syntax


For val_name in range(start,stop):
statements

Example of For Loop


for i in range(1,5):
print(i)
Output :-
1
2
3
4

The range() Function In Python


The range() function is a built-in that is used to iterate over a sequence of numbers.

Syntax Of range() Function range(start, stop)

The range() Function Parameters

Python programming Bhavani M


34 | P a g e

start: Starting number of the sequence.


stop: Generate numbers up to, but not including this number.

Example2:
for i in range(10):
print(i)
output:
0
1
2
3
4
5
6
7
8
9
Note: In above example i did not given starting range, so by default it will take value 0

Example:
for loop to display the multiplication table of 5.

num = 5
for i in range(1, 11):
print(num, 'x', i, '=', num*i)
output:
5x1=5
5 x 2 = 10
5 x 3 = 15
5 x 4 = 20
5 x 5 = 25
5 x 6 = 30
5 x 7 = 35
5 x 8 = 40
5 x 9 = 45
5 x 10 = 50

Nested Loops In Python:


In Python programming language there are two types of loops which

Python programming Bhavani M


35 | P a g e

are for loop and while loop. Using these loops we can create nested loops in Python. Nested
loops mean loops inside a loop. For example, while loop inside the for loop, for loop inside the
for loop, etc.
Python Nested Loops Syntax:
Outer_loop Expression:
Inner_loop Expression:
Statement inside inner_loop
Statement inside Outer_loop

Printing multiplication table using Python nested for loops

for a in range(1,3):
for b in range(1, 11):
print(a, "x", b, "=", a*b)

output:
1X1=1
1X2=2
1X3=3
1X4=4
1X5=5
1X6=6
1X7=7
1X8=8
1X9=9
1 X 10 = 10
2X1=2
2X2=4
2X3=6
2X4=8
2 X 5 = 10
2 X 6 = 12
2 X 7 = 14

Python programming Bhavani M


36 | P a g e

2 X 8 = 16
2 X 9 = 18
2 X 10 = 20

Loop control statements or transfer statements


Using loops in Python automates and repeats the tasks in an efficient manner.
But sometimes, there may arise a condition where you want to exit the loop
completely, skip an iteration or ignore that condition.
These can be done by loop control statements.
Loop control statements change execution from its normal sequence. When
execution leaves a scope, all automatic objects that were created in that scope are
destroyed.
python supports the following control statements.
Break statement
Continue statement
Pass statement

Break statement:
The break statement is used to terminate the loop or statement in which it is present.
After that, the control will pass to the statements that are present after the break
statement, if available.
If the break statement is present in the nested loop, then it terminates only those loops
which contains break statement.

Syntax:
break

Program:
for a in range(1,11):
print(a)
if a==5:
break

Python programming Bhavani M


37 | P a g e

output:
1
2
3
4

Continue statement:
Continue is also a loop control statement just like the break statement.
continue statement is opposite to that of break statement, instead of terminating the loop,
it forces to execute the next iteration of the loop.
As the name suggests the continue statement forces the loop to continue or execute the
next iteration.
When the continue statement is executed in the loop, the code inside the loop following
the continue statement will be skipped and the next iteration of the loop will begin.
Syntax:
Continue

program to print odd numbers by using continue


for a in range(1,11)
if a%2==0:
continue
else:
print(a)

output:
1
3
5
7
9

Pass statement:
As the name suggests pass statement simply does nothing.
The pass statement in Python is used when a statement is required syntactically but you
do not want any command or code to execute.
It is like null operation, as nothing will happen if it is executed.
Python programming Bhavani M
38 | P a g e

Pass statement can be used for writing empty loops, control statement, function and
classes.
Syntax:
pass Program:
if “a” in “india”:pass

EXIT() FUNCTION IN PYTHON

The exit() function in Python is used to exit or terminate the current running script or
program.
You can use it to stop the execution of the program.
When the exit() function is called, the program will immediately stop running and
exit.

for i in range(10):
if i == 5:
print(exit) # prints the exit message
exit()
print(i)

Output
0
1
2
3
4

EXCEPTION HANDLING

Exception
An exception is an event, which occurs during the execution of a program that disrupts
the normal flow of the program's instructions.
When a Python encounters a situation that it cannot cope with it raises an exception.
Python programming Bhavani M
39 | P a g e

When a Python script raises an exception, it must either handle the


exception immediately otherwise it terminates and quits.

Common Examples for Exception:


Division by Zero
Accessing a file which does not exist.
Addition of two incompatible types
Trying to access a non-existent index of a sequence
Removing the table from the disconnected database server.
ATM withdrawal of more than the available amount

Rules of Exceptions
Exceptions must be class objects
For class exceptions, you can use try statement with an except clause
which mentions a particular class.
Even if a statement or expression is syntactically correct, it may display
an error when an attempt is made to execute it.

Different types of exceptions in python or Types of errors:


In Python, there are several built-in exceptions that can be raised when an error
occurs during the execution of a program.
Here are some of the most common types of exceptions in Python:
SyntaxError: This exception is raised when the interpreter encounters a
syntax error in the code, such as a misspelled keyword, a missing colon,
or an unbalanced parenthesis.
TypeError: This exception is raised when an operation or function is
applied to an object of the wrong type, such as adding a string to an
integer.
NameError: This exception is raised when a variable or function name is

Python programming Bhavani M


40 | P a g e

not found in the current scope.


IndexError: This exception is raised when an index is out of range for a
list, tuple, or other sequence types.
KeyError: This exception is raised when a key is not found in a
dictionary.
ValueError: This exception is raised when a function or method is called
with an invalid argument or input, such as trying to convert a string to an
integer when the string does not represent a valid integer.
AttributeError: This exception is raised when an attribute or method is
not found on an object, such as trying to access a non-existent attribute of
a class instance.
IOError: This exception is raised when an I/O operation, such as reading
or writing a file fails due to an input/output error.
ZeroDivisionError: This exception is raised when an attempt is made to
divide a number by zero.
ImportError: This exception is raised when an import statement fails to
find or load a module.
Exception handling
Exception handling enables a program to deal with exceptions and
continue its normal execution.
An error that occurs at runtime is also called an exception.
The run-time exceptions immediately terminate a running program.
Python provides a standard mechanism called exception handling that
allows the program to catch the error and prompt the user to correct the
issue
The syntax for exception handling is to wrap the code that might raise (or
throw) an exception in a try clause, as follows:
try:
<body>

Python programming Bhavani M


41 | P a g e

except <ExceptionType>:
<handler>
Here, <body> contains the code that may raise an exception. When an
exception occurs, the rest of the code in <body> is skipped.
If the exception matches an exception type, the corresponding handler is
executed.
<handler> is the code that processes the exception.
Example:
Def divide(a,b):
try:
c = a/b
return c
except:
print ("Error in divide function")
print(divide(10,0))#function call

Advantages of Exception Handling:


Improved program reliability: By handling exceptions properly, you
can prevent your program from crashing or producing incorrect results
due to unexpected errors or input.
Simplified error handling: Exception handling allows you to separate
error handling code from the main program logic, making it easier to read
and maintain your code.
Cleaner code: With exception handling, you can avoid using complex
conditional statements to check for errors, leading to cleaner and more
readable code.
Easier debugging: When an exception is raised, the Python interpreter
prints a traceback that shows the exact location where the exception
occurred, making it easier to debug your code.

Python programming Bhavani M


42 | P a g e

Disadvantages of Exception Handling:


Performance overhead: Exception handling can be slower than using
conditional statements to check for errors, as the interpreter has to perform
additional work to catch and handle the exception.
Increased code complexity: Exception handling can make your code more
complex, especially if you have to handle multiple types of exceptions or
implement complex error handling logic.
Possible security risks: Improperly handled exceptions can potentially
reveal sensitive information or create security vulnerabilities in your code, so
it‟s important to handle exceptions carefully and avoid exposing too much
information about your program.

Python try...except Block


The try..except block is used to handle exceptions in Python. Here's the syntax
of try..except block:
try:
# code that may cause exception
except:
# code to run when exception occurs
Here, we have placed the code that might generate an exception inside the
try block. Every try block is followed by an except block.
When an exception occurs, it is caught by the except block. The except
block cannot be used without the try block.

Example: Exception Handling Using try...except


try:
numerator = 10
denominator = 0

Python programming Bhavani M


43 | P a g e

result = numerator/denominator
print(result)
except:
print("Error: Denominator cannot be 0.")
# Output: Error: Denominator cannot be 0.
In the example, we are trying to divide a number by 0.
Here, this code generates an exception. To handle the exception, we have put
the code, result = numerator/denominator inside the try block.
Now when an exception occurs, the rest of the code inside the try block is
skipped.
The except block catches the exception and statements inside the except block
are executed. If none of the statements in the try block generates an exception,
the except block is skipped.

Catching Specific Exceptions in Python


For each try block, there can be zero or more except blocks.
Multiple except blocks allow us to handle each exception differently.
The argument type of each except block indicates the type of exception that can
be handled by it.
For example,
try:
even_numbers = [2,4,6,8]
print(even_numbers[5])
except ZeroDivisionError:
print("Denominator cannot be 0.")
except IndexError:
print("Index Out of Bound.") # Output: Index Out of Bound
Run Code
In this example, we have created a list named even_numbers.

Python programming Bhavani M


44 | P a g e

Since the list index starts from 0, the last element of the list is at index 3.
Notice the statement, print(even_numbers[5])
Here, we are trying to access a value to the index 5. Hence, IndexError
exception occurs. When the IndexError exception occurs in the try block,
The ZeroDivisionError exception is skipped.
The set of code inside the IndexError exception is executed.

Python try with else clause


In some situations, we might want to run a certain block of code if the code
block inside try runs without any errors.
For these cases, you can use the optional else keyword with the try statement.
Let's look at an example:
# program to print the reciprocal of even numbers try:
num = int(input("Enter a number: "))
num % 2 == 0
except:
print("Not an even number!")
else:
reciprocal = 1/num
print(reciprocal)

Output
If we pass an odd number:
Enter a number: 1 Not an even number!
If we pass an even number, the reciprocal is computed and displayed.
Enter a number: 4 0.25
However, if we pass 0, we get ZeroDivisionError as the code block inside else
is not handled by preceding except.
Note: Exceptions in the else clause are not handled by the preceding except

Python programming Bhavani M


45 | P a g e

clauses.
Python try...finally
In Python, the finally block is always executed no matter whether there is an
exception or not. The finally block is optional. And, for each try block, there
can be only one finally block.
Let's see an example
try:
numerator = 10
denominator = 0
result = numerator/denominator print(result)
except:
print("Error: Denominator cannot be 0.")
finally:
print("This is finally block”)

Output
Error: Denominator cannot be 0. This is finally block.
In the above example, we are dividing a number by 0 inside the try block. Here,
this code generates an exception.
The exception is caught by the except block. And, then the finally block is
executed.

Function
Python programming Bhavani M
46 | P a g e

Function is a group of related statements that perform a specific task.


Functions help break our program into smaller and modular chunks. As our
program grows larger and larger, functions make it more organized and
manageable.
It avoids repetition and makes code reusable.
Python functions once defined can be called many times in a program.
User-defined and built-in functions are the two main categories of functions
in Python.

Built-in functions:- Python has several functions that are readily available for
use. These functions are called built- in functions.
Ex: abs(),all().ascii(),bool()………so on….

Abs():-returns absolute value of a number

All():-returns true when all elements in iterable is true

Bin():-converts integer to binary string

Bool():-Converts a Value to Boolean

Example:- integer = -20


print('Absolute value of -20 is:', abs(integer))
Output:-Absolute value of -20 is: 20

User-defined functions- Functions defined by the users to do certain specific


task are referred as user-defined function
Example:
def add_numbers(x,y):

Python programming Bhavani M


47 | P a g e

Sum=x+y
Return(sum)
print("The sum is", add_numbers(5, 20))

Output:
The sum is 25

Defining a function

def function_name( parameters ):

The beginning of a function header is indicated by a keyword called def.


Function name is the function's name that we can use to separate it from
others. We will use this name to call the function later in the program.
The function header is terminated by a colon (:).
The body of the function is made up of several valid Python statements. The
indentation depth of the whole code block must be the same (usually 4
spaces).
We can use a return expression to return a value from a defined function.

Calling a Function
Calling a function executes the code in the function.
In a function‟s definition, you define what it is to do. To use a function, you
have to call or invoke it.
The program that calls the function is called a caller.

Parameters and arguments:


Python programming Bhavani M
48 | P a g e

Parameters are passed during the definition of function


Arguments are passed during the function call.

Example:
def add(a,b): here a and b are parameters
result=add(12,13)#12 and 13 are arguments
print(result)

Types of function arguments

There are various ways to use arguments in a function. In Python, we have the
following 4 types of function arguments.
• Keyword arguments
• Default arguments
• Variable length arguments
• Positional arguments

Keyword Arguments
When we call a function with some values, these values get assigned to
the arguments according to their position.
Python allows functions to be called using keyword arguments. When we
call functions in this way, the order (position) of the arguments can be
changed.
If you have some functions with many parameters and you want to
specify only some of them, then you can give values for such parameters
by naming them this is called keyword arguments we use the name
(keyword) instead of the position to specify the arguments to the function.
Example:
Python programming Bhavani M
49 | P a g e

Def display(a,b):
Print(a,b)
display(b=20,a=10)

Default Arguments
In a function, arguments can have default values.
We assign default values to the argument using the „=‟ (assignment)
operator at the time of function definition.
You can define a function with any number of default arguments.
The default value of an argument will be used inside a function if we do
not pass a value to that argument at the time of the function call. Due to
this, the default arguments become optional during the function call.
It overrides the default value if we provide a value to the default
arguments during function calls.

Example:

Let‟s define a function student() with four arguments name, age, grade,
and school.
In this function, grade and school are default arguments with default
values.
If you call a function without school and grade arguments, then the
default values of grade and school are used.
The age and name parameters do not have default values and are
required (mandatory) during a function call.

def student(name, age, grade="Five", school="ABC School"):


print('Student Details:', name, age, grade, school)
student('Jon', 12)

Python programming Bhavani M


50 | P a g e

Output:
Student Details: Jon 12 Five ABC School

Variable-length arguments
Sometimes you may need more arguments to process function than you
mentioned in the definition.
If we don‟t know in advance about the arguments needed in function, you
can use variable-length arguments also called arbitrary arguments.
For this an asterisk (*) is placed before a parameter in function definition
which can hold non-keyword variable-length arguments and a double
asterisk (**) is placed before a parameter in function which can hold
keyword variable-length arguments.

Example
def wish(*names):
"""This function greets all
the person in the names tuple."""
print("Hello",name)
wish("MRCET","CSE","SIR","MADAM")

Output:
Hello MRCET Hello CSE Hello SIR Hello MADAM

Positional Arguments:
Positional arguments are those arguments where values get assigned to the
arguments by their position when the function is called.
For example, the 1st positional argument must be 1st when the function is
called. The 2nd positional argument needs to be 2nd when the function is called,

Python programming Bhavani M


51 | P a g e

etc.
By default, Python functions are called using the positional arguments.
Example: Program to subtract 2 numbers using positional arguments.
def data(name, roll no):

Example:
Def display(a,b):
Print(a,b)
Display(a=10,b=20) #For a 10 will be assigned and for b 20will be assigned

Command Line Arguments in Python


The arguments that are given after the name of the program in the
command line shell of the operating system are known as Command Line
Arguments.
Python provides Using sys.argv
The sys module provides functions and variables used to manipulate
different parts of the python runtime environment.
This module provides access to some variables used or maintained by the
interpreter and to functions that interact strongly with the interpreter.
One such variable is sys.argv which is a simple list structure. It‟s main
purpose are
 It Is a list of command line arguments.
 len(sys.argv) provides the number of command line arguments.
 sys.argv[0] is the name of the current Python script.
Example: Python script for adding two numbers and the numbers are passed as
command-line arguments.
import sys
# total arguments
n = len(sys.argv)
Python programming Bhavani M
52 | P a g e

print("Total arguments passed:", n)


# Arguments passed
print("\n Name of Python script:", sys.argv[0])
print("\n Arguments passed:", end = " ")
for i in range(1, n):
print(sys.argv[i], end = " ")
# Addition of numbers
Sum = 0
# Using arg parse module
for i in range(1, n):
Sum += int(sys.argv[i])
print("\n\nResult:", Sum)

Recursion
Recursion is the process of defining something in terms of itself.
A function that call itself until a given condition is satisfied is called
recursive function

Following is an example of recursive function to find the factorial of an integer


def fact(x):
if X==0 or X==1:
result=1
else:
result = x * fact(x-1)
n=int(input(“enter a number”))
result=fact(x)
print (result)

Python programming Bhavani M


53 | P a g e

Parameter passing mechanism


When we define a function in python we may need to specify parameter
names between the function‟s parentheses.
If we specify parameters in the function definition, then we need to pass
argument i.e values to the function‟s parameters while calling it.
The function use that passed values during its execution by referencing it
via parameter name.
Basically, there are two ways to pass argument values to the function‟s
parameters.
• Call/Pass by Value
• Call/Pass by Reference

Call/Pass by Value in Python


In pass by value (also known as call by value), the argument passed to the
function is the copy of of its original object.
If we change or update the value of object inside the function, then
original object will not change.
If the argument is variable, the copy of the current value of the variable
is passed to the function‟s parameter.
The value of the variable in the function call is not affected by what
happens inside the function. If the argument is passed by value, a copy of
it is made and passed to the function.
If the argument values being passed to the function is large, the copying
can take up a lot of time and memory.
Example
def my_pass_by_value(b):
b += 2
print(b)
c=my_pass_by_value(20)
Python programming Bhavani M
54 | P a g e

print(c)
Output: 22

Call/Pass by Reference
In pass by reference (also known as call by reference), the argument
passed to the function‟s parameter is the original object.
If we change the value of object inside the function, the original object
will also change.
Example
def my_pass_by_reference(r):
r += 10
print(r)
ref1=100
h=my_pass_by_reference(ref1)
print(h)
Output 110

Python programming Bhavani M

You might also like