0% found this document useful (0 votes)
6 views

python

The document provides a comprehensive overview of Python, detailing its history, features, and various implementations. It highlights Python's simplicity, ease of learning, and dynamic typing, as well as its platform independence and extensive libraries. Additionally, it discusses memory management, garbage collection, and compares Python with C and Java programming languages.

Uploaded by

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

python

The document provides a comprehensive overview of Python, detailing its history, features, and various implementations. It highlights Python's simplicity, ease of learning, and dynamic typing, as well as its platform independence and extensive libraries. Additionally, it discusses memory management, garbage collection, and compares Python with C and Java programming languages.

Uploaded by

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

III SEMESTER

Introduction

•Python is a simple, general purpose, high level, and


object-oriented programming language.

•It is used for:


o web development (server-side),
o software development
o AI, etc
History of Python
•Python was initially designed by Guido van Rossum in
1991 and developed by Python Software Foundation.

•Van Rossum picked the name Python for the new language
from the TV show, Monty Python’s Flying Circus.

•Python is open source software, which means anybody can


freely download form www.python.org and use it to
develop programs.
Features of Python

• Simple
• Easy to learn
• Open source
• High level language
• Dynamically typed
• Platform Independent
• Portable
• Procedure and object oriented
Features of Python

• Interpreted
• Huge library
• Scripting language
• Database Connectivity
• Scalable
• Batteries included
Features of Python contd…

• Simple

Python is a simple programming language. When we read a


python program, we feel like reading English sentences.

It means more clarity and less stress on understanding the


syntax of the language . Hence developing and understanding
programs will become easy.
Features of Python contd…

• Easy to learn

Python uses very few keywords. Its programs use very simple
structure. So, developing programs in python become easy.

Python resembles C language. Most of the language constructs


in C are also available in python. Hence migrating from C to
python is easy for programmers.
Features of Python contd…
• High level language

Programming languages are of two types : low level and high


level.

Low level language uses machine code instructions to develop


programs. High level language use English words to develop
programs.

Python also uses English words in its programs and hence it is


called high level programming language.
Features of Python contd…

• Dynamically typed

Dynamically typed language: These are the languages that do


not require any pre-defined data type for any variable as it is
interpreted at runtime by the machine itself. In these languages,
interpreters assign the data type to a variable at runtime
depending on its value.
This is the meaning of saying that python is dynamically
typed language.
Features of Python contd…
• Platform Independent

When python program is compiled using a python compiler, it


generates byte code. Python’s byte code represents a fixed set of
instructions that run on all operating systems and hardware.

Using a PVM, anybody can run these byte code instructions on


any computer system.

Hence, python programs are not dependent on any specific


operating system.
Features of Python contd…

• Portable

When a program yields the same result on any computer in


the world, then it is called portable program.

Python programs will give the same result since they are
platform independent. Once a python program is written, it can
run on any computer system using PVM.
Features of Python contd…
• Procedure and object oriented

Python is a procedure oriented as well as an object oriented


programming language.

In procedure oriented programming languages(C), the programs


are built using functions and procedures.
procedure is a defined piece of code that can be run multiple times.

But in object oriented languages(C++,java), the programs use


classes and objects. In python everything is treated as object.
Features of Python contd…
• Interpreted

A program code is called source code. After writing a python


program, we should compile the source code using python
compiler.

Python compiler translates the python program into an


intermediate code called byte code. This byte code is then
executed by PVM. Inside the PVM, an interpreter converts the
byte code instructions into machine code so that the processor
will understand and run that machine code to produce results.
Features of Python contd…

• Huge Library

Python has a big library which can be used on any operating


system like UNIX, Windows.

Programmers can develop programs very easily using the


modules available in the python library.
Features of Python contd…

• Scripting language

A scripting language is a programming language that does not


use a compiler for executing the source code.

Rather, it uses an interpreter to translate the source code into


machine code.

Generally, scripting languages perform supporting tasks for a


bigger application or software.
Features of Python contd…

• Database Connectivity

A database represents software that stores and manipulates


data.

For example, oracle is a popular database using which we can


store data in the form of tables and manipulate the data.

Python provides interfaces to connect its programs to all major


databases like oracle, sybase or mysql.
Features of Python contd…

• Scalable

A program would be scalable if it could be moved to another


operating system or hardware and take full advantage of the
new environment in terms of performance.

Python programs are scalable since they can run on any platform
and use the features of the new platform effectively.
Features of Python contd…
• Batteries included

The huge library of python contains several small applications


which are already developed and immediately available to
programmers.

These small packages can be used and maintained easily thus


the programmers need not download separate packages or
applications in many cases. These libraries are called batteries
included.

Example of packages are : CherryPy, jellyfish, numpy etc.


Execution of Python program
Flavours of Python
•Flavors of Python refer to the different types of Python
compilers.
•These flavors are useful to integrate various programming
languages into Python.
•The following are some of them:
•CPython:
• This is the standard Python compiler implemented in C language.
• This is the Python software being downloaded and used by
programmers directly from CPython .
• In this, any Python program is internally converted into byte code
using C language functions. This byte code is run on the interpreter
available in Python Virtual Machine (PVM) created in C language.
• The advantage is that it is possible to execute C and C++ functions
and programs in CPython.
•Jython:
•This is earlier known as JPython. This is the implementation
of Python programming language which is designed to run
on Java platform.
•Jython compiler first compiles the Python program into
Java byte code. This byte code is executed by Java Virtual
Machine (JVM) to produce the output. Jython contains
libraries which are useful for both Python and Java
programmers.
•IronPython:
•This is another implementation of Python language for
.NET framework.
• This is written in C# (C Sharp) language.
•The Python program when compiled gives an intermediate
language (IL) which runs on Common Language Runtime
(CLR) to produce the output. This flavor of Python gives
flexibility of using both the .NET and Python libraries.
• PyPy:
• This is Python implementation using Python language.
• Actually, PyPy is written in a language called RPython which was created
in Python language.
• RPython is suitable for creating language interpreters. PyPy programs
run very fast since there is a JIT (Just In Time) compiler added to the
PVM.
• RubyPython:
• This is a bridge between the Ruby and Python interpreters. It encloses a
Python interpreter inside Ruby applications.
• StacklessPython:
• Small tasks which should run individually are called tasklets.
• Tasklets run independently on CPU and can communicate with others via
channels.
• A channel is a manager that takes care of scheduling the tasklets,
controlling them and suspending them. A thread is a process which runs
hundreds of such tasklets. We can create threads and tasklets in
StacklessPython which is reimplementation of original Python language.
•Pythonxy:
•This is pronounced as Python xy and written as
Python(X,Y).
•This is the Python implementation that we get after
adding scientific and engineering related packages.
•AnacondaPython:
•When Python is redeveloped for handling large-scale data
processing, predictive analytics and scientific computing,
it is called Anaconda Python. This implementation mainly
focuses on large scale of data.
Python Virtual Machine
• We know that computers understand only machine code that
comprises 1s and 0 s.
• Since computer understands only machine code, it is imperative that
we should convert any program into machine code before it is
submitted to the computer for execution.
• For this purpose, we should take the help of a compiler. A compiler
normally converts the program source code into machine code.
• A Python compiler does the same task but in a slightly different
manner. It converts the program source code into another code,
called byte code.
•The role of Python Virtual Machine (PVM) is to convert the
byte code instructions into machine code so that the
computer can execute those machine code instructions and
display the final output.
•To carry out this conversion, PVM is equipped with an
interpreter. The interpreter converts the byte code into
machine code and sends that machine code to the computer
processor for execution.
•Since interpreter is playing the main role, often the Python
Virtual Machine is also called an interpreter.
Frozen Binaries
•When a software is developed in Python, there are
two ways to provide the software to the end user.
•The first way is to provide the .pyc files to the user.
•The user will install PVM in his computer and run
the byte code instructions of the .pyc files.
•The other way is to provide the .pyc files, PVM
along with necessary Python library.
•In this method, all the .pyc files, related Python
library and PVM will be converted into a single
executable file (generally with .exe extension) so
that the user can directly execute that file by double
clicking on it.
•In this way, converting the Python programs into
true executables is called frozen binaries. But frozen
binaries will have more size than that of simple .pyc
files since they contain PVM and library files also.
•For creating frozen binaries, we need to use other
party software.
•For example, py2exe is a software that produces
frozen binaries for Windows operating system.
•We can use pyinstaller for UNIX or LINUX.
•Freeze is another program from Python
organization to generate frozen binaries for UNIX.
Memory Management in Pyhton
•In C or C++, the programmer should allocate and
deallocate (or free) memory dynamically, during
runtime.
• For example, to allocate memory, the programmer
may use malloc() function and to deallocate the
memory, he may use the free() function.
•But in Python, memory allocation and deallocation
are done during runtime automatically. The
programmer need not allocate memory while
creating objects or deallocate memory when
deleting the objects.
•Python's PVM will take care of such issues.
Everything is considered as an object in Python.
•For example, strings are objects. Lists are objects.
Functions are objects. Even modules are also
objects. For every object, memory should be
allocated.
•Memory manager inside the PVM allocates memory
required for objects created in a Python program.
All these objects are stored on a separate memory
called heap.
•Heap is the memory which is allocated during
runtime. The size of the heap memory depends on
the Random Access Memory (RAM) of our
computer and it can increase or decrease its size
depending on the requirement of the program.
•We know that the actual memory (RAM) for any
program is allocated by the underlying Operating
system. On the top of the Operating system, a raw
memory allocator oversees whether enough
memory is available to it for storing objects. On the
top of the raw memory allocator, there are several
object-specific allocators operate on the same
heap.
•These memory allocators will implement different
types of memory management policies depending
on the type of the objects.
•For example, an integer number should be stored in
memory in one way and a string should be stored in
a different way.
Garbage Collection in Python
•A module represents Python code that performs a specific
task. Garbage collector is a module in Python that is useful
to delete objects from memory which are not used in the
program.
•The module that represents the garbage collector is named
as gc. Garbage collector in the simplest way to maintain a
count for each object regarding how many times that object
is referenced (or used).
•When an object is referenced twice, its reference count will
be 2.
•When an object has some count, it is being used in the
program and hence garbage collector will not remove it
from memory.
•When an object is found with a reference count 0,
garbage collector will understand that the object is
not used by the program and hence it can be
deleted from memory.
•Hence, the memory allocated for that object is
deallocated or freed.
•Garbage collector can detect reference cycles.

A B C
• Even if the objects A, B and C are no longer used in the Python
program, still these objects contain 1 reference to each one. Since
the reference count for each object is 1, the garbage collector will
not remove these objects from memory.
• These objects stay in memory even after the program execution
completes. To get around this, garbage collector uses an algorithm
(logic) for detecting reference cycles and removing objects in the
cycle.
• Garbage collector classifies the objects into three generations.
• The newly created objects are considered as generation 0 objects.
First time, when the garbage collector examines the objects in
memory and does not remove an object from memory due to the
reason that the object is used by the program, then that object is
placed into next generation, say generation 1.
• When the garbage collector intends to delete the objects for the
second time and the object also survives for the second time, then it
is placed into generation 2.
• Thus, older objects belong to generation 2.,
•Garbage collector tries to delete younger objects which
are not referenced in the program rather than the old
objects.
•Garbage collector runs automatically.
•In some cases, where reference cycles are found in the
program, it is better to run the garbage collector
manually.
•For this purpose, collect() method of gc module can be
used.
•Manual garbage collection can be done in two ways:
time-based and event-based. If the garbage collector is
called in certain intervals of time, it is called time-based
garbage collection.
•If the garbage collector is called on the basis of an event,
for example, when the user disconnects from an
application, it is called event-based garbage collection.
C vs Python
C Python

C Python C is procedure-oriented
Python is object-oriented oriented language. It
programming language. It does not contain the
contains features like classes, objects,
features like classes, objects, inheritance,
inheritance, polymorphism, etc.
polymorphism, etc.

Pointers concept is available in C. Python does not use pointers.


C has do... while, while and for loops. Python has while and for loops.
C has switch statement. Python does not have switch statement.
The variable in for loop does not increment The variable in the for loop increments
automatically. automatically.
C programs execute faster. Python programs are slower compared to C.
It is compulsory to declare the datatypes of
Type declaration is not required in Python.
variables, arrays etc. in C.
C Python
C does not have exception handling facility Python handles exceptions and hence
and hence C programs are weak. Python programs are robust.

The programmer should allocate and Memory allocation and deallocation is done
deallocate memory using automatically by PVM.
malloc(), calloc(), realloc() or free()
functions.
C does not contain a garbage collector. Automatic garbage collector is available in
Python.
C supports single and multi-dimensional Python supports only single dimensional
arrays. arrays. To work with multi-dimensional
arrays, we should use third party
applications like numpy.
The array index should be positive integer. Array index can be positive or negative
integer number. Negative index represents
locations from the end of the array.
C does not have exception handling facility Python handles exceptions and hence
and hence C programs are weak. Python programs are robust.
The programmer should allocate and Memory allocation and deallocation is done
deallocate memory using automatically by PVM.
malloc(), calloc(), realloc() or free()
functions.
Java vs Python
Java Python
Java is object-oriented Python blends the functional
programming language. programming with object-oriented
Functional programming features programming features. Lambdas
are introduced into Java 8.0 are already available in Python.
through lambda expressions.
Java language type discipline is Python type discipline is dynamic
static and weak. and strong.
It is compulsory to declare the Type declaration is not required
datatypes of variables, arrays etc. in Python.
in Java.
Java programs are verbose. It Python programs are concise and
means they contain more number compact. A big program can be
of lines. written using very less number of
lines.
Memory allocation and deal Memory allocation and deal
location is done automatically by location is done automatically by
JVM (Java Virtual Machine). PVM (Python Virtual Machine).
The variable in for loop does not The variable in the for loop
increment automatically. But in for increments automatically.
each loop, it will increment
automatically.
Java has do... while, while, for and Python has while and for loops.
for each loops.
Java has switch statement. Python does not have switch
statement.
Java supports single and Python supports only single
multi-dimensional arrays. dimensional arrays. To work with
multi-dimensional arrays, we should
use third party applications
like numpy.
#include<stdio.h> class Addition a = 10
{ b = 20
void main()
public static void main(String print("The Sum : ",(a+b))
args[ ])
{
{

int a,b; int a,b;

a=10; a = 10;

b=20; b = 20;
System.out.println("The Sum :
printf("The Sum : %d",(a+b)); "+(a+b));
}
}
}
Comments in Python
•Comments can be used to explain Python
code.
•Comments can be used to make the code
more readable.
•Comments can be used to prevent execution
when testing code.
•There are two types of comments in Python:
•Single line comments
•Multiline Comments
•Single line comments

•These comments start with a hash symbol (#) and


are useful to mention that the entire line till the
end should be treated as comment.

#This is a comment
print("Hello, World!")

•Comments are non-executable statements,


neither python compiler nor the PVM will execute
them.
•Multi line Comments

#To find sum of two numbers


#This is multi-line comments
#One more commented line

"""
This is first line
This second line
Finally comes third """
'''
This is first line
This second line
Finally comes third '''

• The triple double quotes ("") or triple single quotes ("") are
called 'multi line comments' or block comments'. They are
used to enclose a block of lines as comments.
Docstrings
• Python supports only single line comments.
• Multi line comments are not available in Python.
• The triple double quotes or triple single quotes are actually
not multi line comments but they are regular strings with
the exception that they can span multiple lines.
• Memory will be allocated to these strings internally.
• If these strings are not assigned to any variable, then they
are removed from memory by the garbage collector and
hence these can be used as comments.
•using """ or '''are not recommended for comments by
Python people since they internally occupy memory and
would waste time of the interpreter since the interpreter has
to check them.
•If we write strings inside """ or ''' and if these strings are
written as first statements in a module, function, class or a
method, then these strings are called documentation strings
or docstrings.
•These docstrings are useful to create an API documentation
file from a Python program.
Datatypes in Python
•A datatype represents the type of data stored into a
variable or memory.
•The datatypes which are already available in Python
language are called Built-in datatypes.
•The datatypes which can be created by the
programmers are called User-defined datatypes.
•The built-in datatypes are of five types:
•None Type
•Numeric types
•Sequences
•Sets
•Mappings
None Type
•In Python, the 'None' datatype represents an object
that does not contain any value.
•In languages like Java, it is called 'null' object. But in
Python, it is called 'None' object.
•In a Python program, maximum of only one 'None'
object is provided.
•In Boolean expressions , None data type represents
False.
Numeric Types
•The Numeric type represent numbers.
•There are three sub types:
•int
•float
•complex
int Datatype
•The int datatype represents an integer number.
•An integer number is a number without any decimal
point.
•For example:
a=-57
•In Python, there is no limit for the size of an int
datatype.
float Datatype
•The float datatype represents floating point
numbers.
•Floating point number is a number that contains
decimal point.
•For example:
num=55.67
x=22.55e4 //22.55x103
Complex datatype
•A complex number is a number that is written in the
form of a + bj or a + bJ.
•Here, 'a' represents the real part of the number and
'b' represents the imaginary part of the number.
•The suffix j or 'J' after 'b' indicates the square root
value of -1.
•The parts 'a' and b' may contain integers or floats.
•For example: 3+5j, -1-5.5J, 0.2+10.5J are all complex
numbers.
c1=-1-5.5J
Representing Binary, Octal and
Hexadecimal numbers
•A binary number should be written by prefixing Ob
(zero and b) or OB (zero and B) before the value.
•For example, Ob110110, OB101010011 are treated as
binary numbers.
•Hexadecimal numbers are written by prefixing Ox
(zero and x) or OX (zero and big X) before the value,
as OxA180 or OX11fb91 etc.
• Octal numbers are indicated by prefixing Oo (zero
and small o) or 00 (zero and then O) before the
actual value.
•For example, 00145 or 00773 are octal values.
bool Datatype
•The bool datatype in Python represents boolean
values.
•There are only two boolean values True or False that
can be represented by this datatype.
•Python internally represents True as 1 and False as 0.
•A blank string like " " is also represented as False.
•Conditions will be evaluated internally to either True
or False.
•For example,
a = 10
b = 20
if(a<b): print("Hello") # displays
Sequences in Python
•Sequence represents a group of elements or items.
•There are six types of sequences in Python:
•str
•bytes
•bytearray
•list
•tuple
•range
str Datatype
•str represents string datatype.
• string is represented by group of characters.
•string are enclosed in single quotes or double
quotes.
•For example:
str=“welcome”
str=‘welcome’
•We can also write strings inside “”” (triple double
quotes) or ‘’’(triple single quotes)
•Example:
s= “welcome to python class”
print(s)

s= “welcome to python class”


print(s*2)
The repetition operator is denoted by *
list Datatype
•Lists in Python are similar to arrays in C or Java.
•A list represents a group of elements.
•The main difference between a list and an array is that a list
can store different types of elements but an array can store
only one type of elements.
•Also, lists can grow dynamically in memory. But the size of
arrays is fixed and they cannot grow at runtime.
•Lists are represented using square brackets[ ] and the
elements are written in [ ], separated by comma.
list=[ 20 , 40 , 56.8 ,qwerty ]
b=[20,36,45,'vish','shiv']
print(b)
print(type(b))
print(b[0])
print(b[2:])
print(b[0:3])
b[0]=50
print(b)
tuple datatype
• A tuple is similar to a list.
• A tuple contains a group of elements which can be of different types.
• The elements in the tuple are separated by commas and enclosed in
parentheses ().
• Whereas the list elements can be modified, it is not possible to
modify the tuple elements.
• That means a tuple can be treated as a read-only list.
tpl= (10, -20, 15.5, 'vijay', "Mary")
bytes Datatype
•The bytes datatype represents a group of byte numbers just
like an array does.
•A byte number is any positive integer from 0 to 255 (inclusive).
•bytes array can store numbers in the range from 0 to 255 and
it cannot even store negative numbers.
•For example:
elements=[10,20,0,40,50] #this is list of byte numbers
x=bytes(elements) #convert the list into bytes array
print(x[0]) #display 0th element
•we cannot modify or edit any element in the bytes type array.
bytearray Datatype
•The bytearray datatype is similar to bytes datatype.
•The difference is that the bytes type array cannot be modified
but the bytearray type array can be modified.
•It means any element or all the elements of the bytearray type
can be modified.
•To create a byte array type array, we can use the function
bytearray.
•For example:
elements =[10, 20, 0, 40, 15] # this is a list of byte numbers
X = bytearray(elements) # convert the list into bytearray type
array print(x[0]) # display 0th element
Range
•The range() function returns a sequence of numbers between
the give range.
# create a sequence of numbers from 0 to 3
numbers = range(4)
# iterating through the sequence of numbers
for i in numbers:
print(i)
# Output:

#0
#1
#2
#3
•Syntax of range()
•The range() function can take a maximum of three
arguments:
range(start, stop, step)
•The start and step parameters in range() are
optional.
•Example : range() with Stop Argument
•If we pass a single argument to range(), it means we are
passing the stop argument.
•In this case, range() returns a sequence of numbers starting
from 0 up to the number (but not including the number).

# numbers from 0 to 3 (4 is not included)


numbers = range(4)
print(list(numbers)) # [0, 1, 2, 3]

# if 0 or negative number is passed, we get an empty sequence


numbers = range(-4)
print(list(numbers)) # []
•Example: range() with Start and Stop Arguments
• If we pass two arguments to range(), it means we are passing start and
stop arguments.
• In this case, range() returns a sequence of numbers starting from start
(inclusive) up to stop (exclusive).
# numbers from 2 to 4 (5 is not included)
numbers = range(2, 5)
print(list(numbers)) # [2, 3, 4]

# numbers from -2 to 3 (4 is not included)


numbers = range(-2, 4)
print(list(numbers)) # [-2, -1, 0, 1, 2, 3]

# returns an empty sequence of numbers


numbers = range(4, 2)
print(list(numbers)) # []
• Example : range() with Start, Stop and Step Arguments
• If we pass all three arguments,
• the first argument is start
• the second argument is stop
• the third argument is step
• The step argument specifies the incrementation between two numbers in
the sequence.
# numbers from 2 to 10 with increment 3 between numbers
numbers = range(2, 10, 3)
print(list(numbers)) # [2, 5, 8]

# numbers from 4 to -1 with increment of -1


numbers = range(4, -1, -1)
print(list(numbers)) # [4, 3, 2, 1, 0]

# numbers from 1 to 4 with increment of 1


# range(0, 5, 1) is equivalent to range(5)
numbers = range(0, 5, 1)
print(list(numbers)) # [0, 1, 2, 3, 4]
# incremented by -2
for i in range(25, 2, -2):
print(i, end=" ")
print()
sets datatype
•A set is an unordered collection of items. Every set
element is unique (no duplicates).
•The order of elements is not maintained in the sets.
It means the elements may not appear in the same
order as they are entered into the set.
•Sets can also be used to perform mathematical set
operations like union, intersection, symmetric
difference, etc.
•A set is created by placing all the items (elements)
inside curly braces {}, separated by comma, or by
using the built-in set() function.
•There are two sub types in sets:
•Set datatype
•Frozenset datatype
•Set datatype
•Created by placing all the items (elements) inside curly
braces {}.
s={ 10, 20, 30, 40, 50 }
print(s)
•The update() method is used to add elements to a set.
•remove() method is used to remove any particular
element from set
s.remove(50)
•Frozenset datatype
•It is same as the set datatype.
•Main difference is that the elements in the set datatype
can be modified. Elements of frozenset cannot be
modified.
•We can create frozenset by passing set to frozenset()
function.
s={ 10, 20, 30, 40, 50 }
print(s)
fs=frozenset(s)
print(fs)
# tuple of vowels
vowels = ('a', 'e', 'i', 'o', 'u')

fSet = frozenset(vowels)
print('The frozen set is:', fSet)
print('The empty frozen set is:', frozenset())

# frozensets are immutable


fSet.add('v')
Mapping types
•A map represents a group of elements in the form
of key value pairs so that when the key is given, we
can retrieve the value associated with it.
•The dict datatype is an example for a map.
•The 'dict' represents a 'dictionary' that contains
pairs of elements such that the first element
represents the key and the next one becomes its
value.
•The key and its value should be separated by a
colon (:) and every pair should be separated by a
comma. All the elements should be enclosed inside
curly brackets {}.
d = {10: 'Vish' , 11:'shiv', 12:'chitti' 13:'siddu'}

•D is a name of dictionary. 10 is the key and its


associated value is 'Vish'.
Accessing Elements from Dictionary
•While indexing is used with other data types to
access values, a dictionary uses keys.
•Keys can be used either inside square brackets [] or
with the get() method.
d = {10: 'Vish' , 11:'shiv', 12:'chitti', 13:'siddu'}
print(d[10])
print(d.get(12))
del d[10]
print(d)
# Changing and adding Dictionary Elements
my_dict = {'name': 'Jack', 'age': 26}

# update value
my_dict['age'] = 27

print(my_dict)

# add item
my_dict['address'] = 'Downtown'

print(my_dict)
Literals in Python
•A Literal is a constant value that is stored into a
variable in a program.
•Types of Literals in Python:
•Numeric literals
•Boolean Literals
•String literals
Numeric Literals
•Numeric Literals are immutable (unchangeable).
Numeric literals can belong to 3 different numerical
types: Integer, Float, and Complex.
a = 0b1010 #Binary Literals
b = 100 #Decimal Literal
c = 0o310 #Octal Literal
d = 0x12c #Hexadecimal Literal

#Float Literal
float_1 = 10.5
float_2 = 1.5e2

#Complex Literal
x = 3.14j

print(a, b, c, d)
print(float_1, float_2)
print(x, x.imag, x.real)
String Literals
•A group of characters is called a string literal.
•These string literals are enclosed in single quotes or
double quotes or triple quotes .
• In Python, there is no difference between single
quoted strings and double quoted strings. Single or
double quoted strings should end in the same line.
•When a string literal extends beyond a single line
we should use triple quotes.
Determining the Datatype of a Variable

• To know the datatype of a variable or object, we can use the type()


function.
a=15
print(type(a))
Identifiers and Reserved words
•An identifier is a name that is given to a variable or function
or class etc.
•Identifiers can include letters, numbers, and the underscore
character (_).
•They should always start with a nonnumeric character.
•Special symbols such as ?, #, $, %, and @ are not allowed in
identifiers. S
•Some examples for identifiers are salary, name11,
gross_income, etc.

•Python is a case sensitive programming language. It means


capital letters and small letters are identified separately by
Python.
Naming Conventions in Python

•Python developers made some suggestions to the


programmers regarding how to write names in the
programs. The rules related to writing names of packages,
modules, classes, variables, etc. are called naming
conventions.
•The following naming conventions should be followed:
•Packages: Package names should be written in all lower case
letters. When multiple words are used for a name, we
should separate them using an underscore (__).
•Modules: Module names should be written in all lower case
letters. When multiple words are used for a name, we
should separate them using an underscore (__).
•Classes: Each word of a class name should start with a capital
letter. This rule is applicable for the classes created by us.
Python's built-in class names use all lowercase words. When a
class represents exception, then its name should end with a
word 'Error'.
•Global variables or Module-level variables: Global variables
names should be all lower case letters. When multiple words
are used for a name, we should separate them using an
underscore (_).
•Instance variables: Instance variables names should be all lower
case letters. When multiple words are used for a name, we
should separate them using an underscore. Non-public instance
variable name should begin with an underscore.
•Functions: Function names should be all lower case letters.
When multiple words are used for a name, we should separate
them using an underscore (_).
•Methods: Method names should be all lower case letters.
When multiple words are used for a name, we should
separate them using an underscore (_).
•Method arguments: In case of instance methods, their
first argument name should be 'self. In case of class
methods, their first argument name should be 'cls'.
•Constants: Constants names should be written in all
capital letters. If a constant has several words, then each
word should be separated by an underscore (_).
•Non accessible entities: Some variables, functions and
methods are not accessible outside and they should be
used as they are in the program. Such entities names are
written with two double quotes before and two double
quotes after.
Operators in Python
• An operator is a symbol that performs an operation.
• An operator acts on some variables called operands.
• If an operator acts on a single variable, it is called unary operator.
• If an operator acts on a two variables, it is called Binary operator.
• If an operator acts on a three variables, it is called ternary operator.
Arithmetic operators

• Arithmetic operators are used to perform mathematical operations


like addition, subtraction, multiplication, etc.
x = 15
y=4

print('x + y =',x+y)
print('x - y =',x-y)
print('x * y =',x*y)
print('x / y =',x/y)
print('x // y =',x//y)
print('x ** y =',x**y)
Comparison(Relational) operators

•Comparison operators are used to compare values.


It returns either True or False according to the
condition.
x = 10
y = 12

print('x > y is',x>y)


print('x < y is',x<y)
print('x == y is',x==y)
print('x != y is',x!=y)
print('x >= y is',x>=y)
print('x <= y is',x<=y)
Logical operators

•Logical operators are useful to construct compound


conditions.
•Compound condition is a combination of more than
one simple condition.
•Logical operators are the and, or, not operators.
x = True
y = False

print('x and y is',x and y)

print('x or y is',x or y)

print('not x is',not x)
Bitwise operators
•Bitwise operators act on operands as if they were
strings of binary digits. They operate bit by bit.
# Examples of Bitwise operators
a = 10
b=4
# Print bitwise AND operation
print(a & b)
# Print bitwise OR operation
print(a | b)
# Print bitwise NOT operation
print(~a)
# print bitwise XOR operation
print(a ^ b)
# print bitwise right shift operation
print(a >> 2)
# print bitwise left shift operation
print(a << 2)
Assignment operators
•Assignment operators are used in Python to assign
values to variables.
# Examples of Assignment Operators
a = 10
# Assign value
b=a
print(b)
# Add and assign value
b += a
print(b)
# Subtract and assign value
b -= a
print(b)
# multiply and assign
b *= a
print(b)
# bitwise leftshift operator
b <<= a
print(b)
Identity operators

•is and is not are the identity operators in Python.


They are used to check if two values (or variables)
are located on the same part of the memory.
a = 10
b = 20
c=a
print(a is not b)
print(a is c)
Membership Operators
•in and not in are the membership operators; used
to test whether a value or variable is in a sequence
(string, list, tuple, set and dictionary).
# Python program to illustrate
# not 'in' operator
x = 24
y = 20
list = [10, 20, 30, 40, 50]
if (x not in list):
print("x is NOT present in given list")
else:
print("x is present in given list")

if (y in list):
print("y is present in given list")
else:
print("y is NOT present in given list")
Mathematical Functions
•In Python, a module is a file that contains a group of
useful objects like functions, classes or variables.
•math is a module that contains several functions to
perform mathematical operations.
•If we want to use any module in our Python
program, first we should import that module into
our program by writing 'import' statement. For
example, to import math' module, we can write:

import math
•Once this is done, we can use any of the functions
available in math module. Now, we can refer to
sqrt() function from math module by writing
module name before the function as:
math.sqrt().
•X=math.sqrt(16)
•We can also write import math as m
•X=m.sqrt(16)
•If we want to import only one or two functions from
math module then we can write as follows:
from math import sqrt,factorial
Function Description

Returns the smallest integer greater than or


ceil(x)
equal to x.

copysign(x, y) Returns x with the sign of y

fabs(x) Returns the absolute value of x

factorial(x) Returns the factorial of x

Returns the largest integer less than or


floor(x)
equal to x

Returns the remainder when x is divided by


fmod(x, y)
y

Returns the mantissa and exponent of x as


frexp(x)
the pair (m, e)

Returns an accurate floating point sum of


fsum(iterable)
values in the iterable

Returns True if x is neither an infinity nor a


isfinite(x)
NaN (Not a Number)
sqrt(x) Returns the square root of x

acos(x) Returns the arc cosine of x

asin(x) Returns the arc sine of x

atan(x) Returns the arc tangent of x

atan2(y, x) Returns atan(y / x)

cos(x) Returns the cosine of x

Returns the Euclidean norm, sqrt(x*x


hypot(x, y)
+ y*y)

sin(x) Returns the sine of x

tan(x) Returns the tangent of x

Converts angle x from radians to


degrees(x)
degrees

Converts angle x from degrees to


radians(x)
radians
Control Statements
• Control statements are statements which control or change the flow
of execution.
• The following are the control statements available in Python:
• if statement
• if... else statement
• if... elif... else statement
• while loop
• for loop
• else suite
• break statement
• continue statement
• pass statement
• assert statement
• return statement
if statement
•This statement is used to execute one or more statement
depending on whether condition is True or not.
•The syntax or correct format of if statement is given below.
if condition:
Statements
•First, the condition is tested. If the condition is True, then the
statements given after colon (:) are executed.
•We can write one or more statements after colon (:).
•If the condition is False, then the statements mentioned after
colon are not executed.
•We can also write a group of statements after
colon.
•The group of statements in Python is called a suite.
•While writing a group of statements, we should
write them all with proper indentation.
•Indentation represents the spaces left before the
statements.
•The default indentation used in Python is 4 spaces.
# If the number is positive, we print an appropriate message

num = 3
if num > 0:
print(num, "is a positive number.")
print("This is always printed.")

num = -1
if num > 0:
print(num, "is a positive number.")
print("This is also always printed.")
•Understanding indentation is very important in
Python.
•Indentation refers to spaces that are used in the
beginning of a statement.
•The statements with same indentation belong to
same group called a suite.
•By default, Python uses 4 spaces but it can be
increased or decreased by the programmers.
The if... else statement
•The if... else statement executes a group of statements
when a condition is True; otherwise, it will execute another
group of statements.
•The syntax of if... else statement is given below:
if test expression:
Body of if
else:
Body of else
•The if..else statement evaluates test expression and
will execute the body of if only when the test
condition is True.

•If the condition is False, the body of else is


executed. Indentation is used to separate the
blocks.
# Python program to check if the input number is odd or
even.

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


if (num % 2) == 0:
print("{0} is Even".format(num))
else:
print("{0} is Odd".format(num))
if...elif...else Statement
•Syntax of if...elif...else
if test expression:
Body of if
elif test expression:
Body of elif
else:
Body of else
•The elif is short for else if. It allows us to check for
multiple expressions.

•If the condition for if is False, it checks the condition


of the next elif block and so on.

•If all the conditions are False, the body of else is


executed.

•Only one block among the several if...elif...else blocks


is executed according to the condition.

•The if block can have only one else block. But it can
have multiple elif blocks.
Nested if statements
'''In this program, we input a number check if the number is positive or
negative or zero and display an appropriate message This time we use
nested if statement'''

num = float(input("Enter a number: "))


if num >= 0:
if num == 0:
print("Zero")
else:
print("Positive number")
else:
print("Negative number")
while Loop
•The while loop in Python is used to iterate over a
block of code as long as the test expression
(condition) is true.
•Syntax of while Loop in Python
while test_expression:
Body of while
•In the while loop, test expression is checked first.
The body of the loop is entered only if the
test_expression evaluates to True. After one
iteration, the test expression is checked again. This
process continues until the test_expression
evaluates to False.
# Program to add natural
# numbers up to
# sum = 1+2+3+...+n

# To take input from the user,


n = int(input("Enter n: "))
# initialize sum and counter
sum = 0
i=1

while i <= n:
sum = sum + i
i = i+1 # update counter

# print the sum


print("The sum is", sum)
for Loop
•The for loop in Python is used to iterate over a
sequence (list, tuple, string) or other iterable
objects. Iterating over a sequence is called
traversal.
•Syntax of for Loop
for val in sequence:
loop body
•Here, val is the variable that takes the value of the
item inside the sequence on each iteration.

•Loop continues until we reach the last item in the


sequence. The body of for loop is separated from
the rest of the code using indentation.
# Program to find the sum of all numbers stored in a list

# List of numbers
numbers = [6, 5, 3, 8, 4, 2, 5, 4, 11]

# variable to store the sum


sum = 0

# iterate over the list


for val in numbers:
sum = sum+val

print("The sum is", sum)


x='ABCDEF'
for i in x:
print(i)

x='ABCDEF‘
n=len(x)
for i in range(n):
print(x[i])
#to find sum of list of numbers using for
list=[10,20,30,40,50]
sum=0
for i in list
print(i)
sum+=i
print(‘sum=‘,sum)
The else Suite
•In python it is possible to use ‘else’ statement along with for
loop or while loop.
group1 = [1,2,3,4,5]
search = int(input('Enter element to search:'))
for element in group1:
if search == element:
print('Element found in group')
break #come out of for loop
else:
print('Element not found in group1') #this is else suite
lower = int(input("Enter starting number : "))
upper = int(input("Enter ending number: "))
for num in range(lower,upper + 1):
if num > 1:
for i in range(2,num):
if (num % i) == 0:
break
else:
print(num,end='\t')
The break Statement

• Python break is used to terminate the execution of the loop.


• break statement in Python is used to bring the control out of the
loop when some external condition is triggered.
• break statement is put inside the loop body (generally after if
condition).
• It terminates the current loop, i.e., the loop in which it appears, and
resumes execution at the next statement immediately after the end
of that loop.
• If the break statement is inside a nested loop, the break will
terminate the innermost loop.
# Use of break statement inside the loop

for val in "string":


if val == "i":
break
print(val)

print("The end")
num = 0
for i in range(10):
num += 1
if num == 8:
break
print("The num has value:", num)
print("Out of loop")
Python Continue Statement
•Python Continue Statement skips the execution of
the program block from after the continue
statement and forces the control to start the next
iteration.
•Python Continue statement is a loop control
statement that forces to execute the next iteration
of the loop while skipping the rest of the code
inside the loop for the current iteration only, i.e.
when the continue statement is executed in the
loop, the code inside the loop following the
continue statement will be skipped for the current
iteration and the next iteration of the loop will
begin.
# Program to show the use of continue statement inside loops

for val in "string":


if val == "i":
continue
print(val)

print("The end")
Python pass statement
•The pass statement does not do anything.
•It is used with if statement or inside a loop to represent no
operation.
•In Python programming, the pass statement is a null
statement. The difference between a comment and a pass
statement in Python is that while the interpreter ignores a
comment entirely, pass is not ignored.
•However, nothing happens when the pass is executed. It
results in no operation (NOP).
•Suppose we have a loop or a function that is not
implemented yet, but we want to implement it in
the future. They cannot have an empty body. The
interpreter would give an error. So, we use the pass
statement to construct a body that does nothing.
Python Assert Statement
•The assert statement is useful to check if a
particular condition is fulfilled or not.
•Assertions are simply boolean expressions that
check if the conditions return true or not. If it is
true, the program does nothing and moves to the
next line of code. However, if it's false, the program
stops and throws an error.
•It is also a debugging tool as it halts the program as
soon as an error occurs and displays it.
•Syntax for using Assert in Python:
assert <condition>
assert <condition>,<error message>
def avg(marks):
assert len(marks) != 0,"List is empty."
return sum(marks)/len(marks)

mark2 = [55,88,78,90,79]
print("Average of mark2:",avg(mark2))

mark1 = []
print("Average of mark1:",avg(mark1))
Python return statement
• A return statement is used to end the execution of the function call and
“returns” the result to the caller.
Syntax:
def fun():
statements
.
.
return [expression]
Example:

def cube(x):
r=x**3
return r
# Python program to
# demonstrate return statement
def add(a, b):

# returning sum of a and b


return a + b

def is_true(a):

# returning boolean of a
return bool(a)

# calling function
res = add(2, 3)
print("Result of add function is {}".format(res))
res = is_true(2<5)
print("\nResult of is_true function is {}".format(res))
Functions
•In Python, a function is a group of related statements that
performs 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.
•The following are the advantages of functions:

•Functions are important in programming because they are


used to process data, make calculations or perform any task
which is required in the software development.
•Once a function is written, it can be reused as and when
required. So functions are also called reusable code.
•Functions provide modularity for programming. A module
represents a part of the program. Usually, a programmer
divides the main task into smaller sub tasks called modules.
To represent each module, the programmer will develop a
separate function. Then these functions are called from a
main program to accomplish the complete task. Modular
programming makes programming easy.
•Code maintenance will become easy because of
functions. When a new feature has to be added to
the existing software, a new function can be written
and integrated into the software. Similarly, when a
particular feature is no more needed by the user, the
corresponding function can be deleted or put into
comments.
•When there is an error in software , the
corresponding function can be modified without
disturbing the other functions in the software.
•Will reduce the length of the program.
Difference between Function and Method

•Function contains a group of statements and


performs a specific task.
•A function can be written individually in a Python
program.
•A function is called using its name. When a function
is written inside a class, it becomes a 'method‘.
•A method is called using one of the following ways:
objectname.methodname()
classname.methodname()
•Function and a method are same except their
placement and the way they are called.
Defining a Function

•Syntax of Function
def function_name(parameters):
"""docstring"""
statement(s)
def greet(name):
"""
This function greets to
the person passed in as
a parameter
"""
print("Hello, " + name + ". Good morning!")
•Function definition that consists of the following
components.
•Keyword def that marks the start of the function header.
•A function name to uniquely identify the function.
Function naming follows the same rules of writing
identifiers in Python.
•Parameters (arguments) through which we pass values to
a function. They are optional.
•A colon (:) to mark the end of the function header.
•Optional documentation string (docstring) to describe
what the function does.
•One or more valid python statements that make up the
function body. Statements must have the same
indentation level (usually 4 spaces).
•An optional return statement to return a value from the
function.
Calling a function in python
• Once we have defined a function, we can call it
from another function, program, or even the
Python prompt.
•To call a function we simply type the function name
with appropriate parameters.
def greet(name):
"""
This function greets to
the person passed in as
a parameter
"""
print("Hello, " + name + ". Good morning!")

greet(‘XYZ')
•Note: In python, the function definition should
always be present before the function call.
Otherwise, we will get an error.
Returning results from a function
• We can return the result or output from the function using return
statement in the body of the function.
def square_value(num):
"""This function returns the square
value of the entered number"""
return num**2

print(square_value(2))
print(square_value(-4))
Returning Multiple Values from a function
# A Python program to return multiple
# values from a method using tuple

# This function returns a tuple


def fun():
str = "geeksforgeeks"
x = 20
return str, x; # Return tuple, we could also
# write (str, x)

# Driver code to test above method


str, x = fun() # Assign returned tuple
print(str)
print(x)
# A Python program to return multiple
# values from a method using list

# This function returns a list


def fun():
str = "geeksforgeeks"
x = 20
return [str, x];

# Driver code to test above method


list = fun()
print(list)
PASSING ARGUMENTS TO
FUNCTIONS
• In programming, there are two ways in which arguments can be passed to functions :-
• Pass by Value:
• Function creates a copy of the variable(Object in Python) passed to it as an
argument.
• The actual object is not affected.
• Object is of immutable type, because immutable objects cannot be modified.
• Pass by Reference:
• The actual object is passed to the called function.
• All the changes made to the object inside the function affect its original value.
• Object is mutable type, as mutable objects can be changed, the passed objects are
updated.
EXAMPLES OF PASSING IMMUTABLE
ARGUMENTS

New memory address of ‘a’


OUTPUT:
inside the function.

Actual variable ‘a’ is not


changed.
EXAMPLES OF PASSING MUTABLE ARGUMENTS

Value of my list is
OUTPUT changed after
function call

Address is same
•In python Integers, floats , strings and tuples are
immutable. Their data cannot be modified, when
we try to change the value, a new object is created
with a modified value.
•Lists and dictionaries are mutable, when we change
the data the same object gets modified and new
object is not created.
FUNCTION ARGUMENTS

def add_numbers(a, b):


sum = a + b
print('Sum:', sum)

add_numbers(2, 3)
• In the above example, the function add_numbers() takes two
parameters: a and b.
add_numbers(2, 3)
• Here, add_numbers(2, 3) specifies that parameters a and b will get
values 2 and 3 respectively.
• When a function is defined, it may have some parameters. These
parameters are useful to receive values from outside of the function.
They are called 'formal arguments'.
• When we call the function, we should pass data or values to the
function. These values are called 'actual arguments'.
• In the following code, 'a' and 'b' are formal arguments and 'x' and 'y'
are actual arguments.

def sum(a, b): # a, b are formal arguments


c = a+b
print(c)

# call the function


x=10; y=15
sum(x, y) # x, y are actual arguments
•The actual arguments used in a function call are of 4
types:
•Positional arguments
•Keyword arguments
•Default arguments
•Variable length arguments
Function Argument with Default Values
• Default Argument- argument that assumes a default value if a value is not
provided in the function call for that argument.
• = operator to provide default values.

In this code,
argument ‘b’
has given a default
value.
ie (b=90)

OUTPUT

When the value of ‘b’ is not passed


in function ,then it takes default
argument.
def add_numbers( a = 7, b = 8):
sum = a + b
print('Sum:', sum)

# function call with two arguments


add_numbers(2, 3)

# function call with one argument


add_numbers(a = 2)

# function call with no arguments


add_numbers()
Positional Arguments
•An argument is a variable, value or object passed to a function
or method as input. Positional arguments are arguments that
need to be included in the proper position or order.
•The first positional argument always needs to be listed first
when the function is called. The second positional argument
needs to be listed second and the third positional argument
listed third, etc.

def print_line(line, encoding, errors):


print(line, encoding, errors) OUTPUT
line = 1 321
encoding = 2
errors = 3

print_line(errors, encoding, line)


KEYWORD ARGUMENTS
• Keyword arguments are related to the function calls.
• Using keyword arguments in a function call, the caller identifies the
arguments by the parameter name.
• Allows to skip arguments or place them out of order, the Python
interpreter use the keywords provided to match the values with
parameters.
•Caller identifies the keyword
argument by the parameter
name.
•Calling of the argument
Order
OUTPUT doesn’t matter .
Variable-Length Arguments
•In Python, we can pass a variable number of
arguments to a function using special symbols.
There are two special symbols:
•*args (Non-Keyword Arguments)
•**kwargs (Keyword Arguments)
# Python program to illustrate
# *args for variable number of arguments
def myFun(*argv):
for arg in argv:
print(arg)

myFun('Hello', 'Welcome', 'to', ‘Hubli')


# program to find sum of multiple numbers

def find_sum(*numbers):
result = 0

for num in numbers:


result = result + num

print("Sum = ", result)

# function call with 3 arguments


find_sum(1, 2, 3)

# function call with 2 arguments


find_sum(4, 9)
# Python program to illustrate
# *kwargs for variable number of keyword arguments

def myFun(**kwargs):
for key, value in kwargs.items():
print("%s == %s" % (key, value))

# Driver code
myFun(first=‘hello', mid=‘welcome to', last=‘Hubli')
def fun(value,*val):
print('formal arguments=',value) def fun(value,*val):
print('formal arguments=',value)
for i in val: for i in val:
print(i) print(i)

fun(5,10,20)
fun(5,10,20) fun(10)
Local and Global Variables

•When we declare a variable inside a function it become a


local variable

•A Local variable is a variable whose scope is only limited to


that function Where it is created.

•In the Following example the variable a is declared inside


myfunction() and hence it is available inside that function

•Once we come out of function the variable a is removed


from memory
def myfunction():
a=1 # this is local variable
a=a+1
print(a)

myfunction()
print(a)

Output
Global Variables
•These are those which are defined outside any
function and which are accessible throughout the
program, i.e., inside and outside of every function.
a=1 #this is global variable
def myfunction():
b=2
print('a=', a)#display global variable
print('b=',b)#display local variable
myfunction()
print(a)
print(b)

Output
a=1 #this is global variable
def myfunction():
a=2
print('a=', a)#display global variable

myfunction()
print('a=', a)

Output
The Global Keyword

• sometime the global and local variable may have


same name in that case the function by default
refers to the local variable and ignores the global
variable.
•when the programmer wants to use the global
variable inside a function he can use the key word
global before the variable in the beginning of the
function.
a=1 #this is global variable
def myfunction():
global a
a=2
print('a=', a)#display global variable

myfunction()
print('a=', a)

Output
Passing a Group of Elements to a Function

•To pass a group of elements like numbers or strings,


we can accept them into a list and then pass the list
to the function where the required processing can
be done.
def calculate(lst):
n = len(lst)
sum=0
for i in lst:
sum+=i
avg = sum/n
return sum, avg
lst = [int(x) for x in input('Enter numbers separated by space:').split()]
x, y = calculate(lst)
print('Total:', x)
print('Average:', y)
Recursive Functions
•function can call other functions. It is even possible
for the function to call itself. These types of
construct are termed as recursive functions.
•A function that calls itself is known as recursive
function
def factorial(x):
"""This is a recursive function
to find the factorial of an integer"""

if x == 1:
return 1
else:
return (x * factorial(x-1))

num = 3
print("The factorial of", num, "is", factorial(num))
#recursive function to calculate factorial
def factorial(n):
if n==0:
result=1
else:
result=n*factorial(n-1)
return result

For i in range(1,11):
print(“Factorial of {} is {}”.format(I,factorial(i)))
•Every recursive function must have a base condition
that stops the recursion or else the function calls
itself infinitely.
•The Python interpreter limits the depths of
recursion to help avoid infinite recursions, resulting
in stack overflows.

•By default, the maximum depth of recursion is


1000. If the limit is crossed, it results in
RecursionError.
Lambda/Anonymous Function
•A function without a name is called 'anonymous
function'.
•So far, the functions we wrote were defined using
the keyword 'def'. But anonymous functions are not
defined using 'def'. They are defined using the
keyword lambda and hence they are also called
'Lambda functions'.
• Let's take a normal function that returns square of a given
value.

def square (x):


return x*x

•The same function can be written as anonymous function as:


lambda x: x*x
•Observe the keyword lambda'. This represents that an
anonymous function is being created. After that, we have
written an argument of the function, i.e. 'x'. Then colon (:)
represents the beginning of the function that contains an
expression x * x.
lambda Function Declaration
•We use the lambda keyword instead of def to create a
lambda function. Here's the syntax to declare the lambda
function:
lambda argument(s) : expression
•Here,
•argument(s) - any value passed to the lambda function
•expression - expression is executed and returned
# lambda that accepts one argument
greet_user = lambda name : print('Hey there,', name)

# lambda call
greet_user(‘XYZ')

• Here greet_user is the function name to which the lambda


expression is assigned.
Creating our own modules in Python
•Modules refer to a file containing Python statements and
definitions.

•A file containing Python code, for example: example.py, is


called a module, and its module name would be example.

•We use modules to break down large programs into small


manageable and organized files. Furthermore, modules
provide reusability of code.

•We can define our most used functions in a module and


import it, instead of copying their definitions into different
programs.
# save this code as employee.py
# to calculate dearness allowance

def da(basic):
da = basic *80/100
return da

def hra(basic):
hra=basic*15/100
return hra

def pf(basic):
pf=basic *12/100
return pf

def itax(gross):
tax =gross*0.1
return tax
# using employee module to calculate gross and net salaries of an employee
from employee import *

# calculate gross salary of employee by taking basic


basic = float(input('Enter basic salary: '))
# calculate gross salary
gross = basic+da (basic) +hra (basic)
print('Your gross salary: {:10.2f}'. format (gross))

# calculate net_salary
net = gross - pf (basic)-itax (gross)
print("Your net salary: {:10.2f}'. format (net))

You might also like