SlideShare a Scribd company logo
PYTHON PROGRAMMING - INTRODUCTION,
DATA TYPES, OPERATORS, CONTROL FLOW
STATEMENTS, FUNCTIONS & LAMBDA
EXPRESSIONS
Ms. V.SAROJA
Assistant Professor
Department of Computer Science and Engineering
SRM Institute of Science and Technology, Chennai
INTRODUCTION
• General purpose programming language
• Object oriented
• Programming + scripting language
• Interactive
• Interpreted
• High level programming
• Open source
• Powerful
– Dynamic typing
– Builtin types and tools
– Library utilities
– Third party utilities(Numpy, Scipy)
• Portable
• Easy to understand
• Flexible – no hard rules
• More flexible in solving problems using different methods
• Developer productivity
• Support libraries
• Software quality
• Access to advanced mathematical, statistical and
database functions
Compiler
• A compiler is a program that converts a
program written in a programming language
into a program in the native language, called
machine language, of the machine that is to
execute the program.
From Algorithms to Hardware
(with compiler)
Algorithm
Program
A real computer
Translate (by a human being)
Translate (by compiler program)
The Program Development Process
(Data Flow)
Editor
Compiler
A real computer
Algorithm
Program in programming language
Program in machine’s language
Input Output
The Program Development Process
(Control Flow)
Edit
Compile
Run
Syntax errors
Input Output
Runtime errors
Interpreter
• An alternative to a compiler is a program
called an interpreter. Rather than convert our
program to the language of the computer, the
interpreter takes our program one statement
at a time and executes a corresponding set of
machine instructions.
Interpreter
Edit
Interpreter
Syntax or runtime errors
Input
Output
• Python versions
– Python 2(released on16th october 2000)
– Python 3(released on 3rd december 2008 with more
testing and new features)
• Derived from other languages – C,C++, Unix,
Shell, Smalltalk, Algol-68
• Different python implementation
– Jython
– IronPython
– Stackless Python
– PyPy
Applications of Python
• System programming
• Desktop applications
• Database applications
• Internet scripting
• Component integration
• Rapid prototyping
• Web mapping
• Computer vision for image and video processing
• Gaming, XML, Robotics
• Numeric and scientific programming
2 modes for using Python interpreter
• Interactive mode
– Without creating python script file and passing it to interpreter, directly
execute code to python prompt
• Eg.
>>> print("hello world")
hello world
>>> x=[0,1,2,3.5,”hai”]
>>> x
>>> [0, 1, 2, 3.5, “hai”]
>>> 2+3
>>> 5
>>> len(‘hello’)
>>> 5
>>> ‘hello’ + ‘welcome’
>>> ‘hello welcome’
Running Python in script mode
• programmers can store Python script source code in a
file with the .py extension, and use the interpreter to
execute the contents of the file.
• To execute the script by the interpreter, the name of
the file is informed to the interpreter.
• For example, if source script name MyFile.py,
to run the script on Unix: python MyFile.py
• Working with the interactive mode is better when
Python programmers deal with small pieces of code as
you can type and execute them immediately, but when
the code is more than 2-4 lines, using the script for
coding can help to modify and use the code in future
Syntax and Semantics
• Comments in python begin by #
– Ignored by interpreter
– Standalone comments/inline comments # ------
– Multiline comments /* ---------- ----- */
• End of line marker “” in multiline expression
– Within parenthesis no need of “”
• Code blocks are denoted by indentation
– Indented code block preceded by : on previous line
• Whitespaces within line does not matter
• Parenthesis are for grouping or calling
• Eg.
• x=5,y=0
• if x<4:
y=x*2
print(y)
• if x<4:
y=x*2
print(y)
Frameworks
• Anaconda
– Anaconda is free and open source distribution of Python
and R programming language for data science and
machine learning related applications. It simplify package
management and deployment using package management
system conda
• Jupyter
– Jupyter Notebook is a open source web application that
allow to create and share documents contain live code,
equations, visualizations. Also used for data cleaning and
transformation, numerical simulation, statistical modeling,
data visualization, machine learning
Comments
• Often we want to put some documentation in
our program. These are comments for
explanation, but not executed by the
computer.
• If we have # anywhere on a line, everything
following this on the line is a comment –
ignored
To run python interactively
• IDLE (Python 3.7 – 32bit)
• IDLE (Python 3.10 – 64bit)
• Desktop GUI that edit, run, browse and debug python
programs (all from single interface)
• Features
– 100% pure python
– Cross platform(same on windows, unix, Mac os)
– 2 windows
• Python Shell window(interactive python interpreter) with colorizing of
code, input, output, error message
• Editor window(undo, colorizing, smart indent, auto completion &
other features)
– Debugging with breakpoints, stepping and viewing of global &
local namespaces
IDLE – Development Environment
• IDLE helps you program
in Python by:
– color-coding your
program code
– debugging
– auto-indent
– interactive shell
19
Example Python
• Hello World
print “hello world”
• Prints hello world to
standard out
• Open IDLE and try it out
• Follow along using IDLE
20
• IDLE usability features:
– Auto indent and un-indent for python code
– Auto completion
– Balloon helps popups the syntax for particular
function call when type (
– Popup selection list of attributes and methods
when type classname/modulename .
– Either pause or press Tab
• Other most commonly used IDEs for Python
– Eclipse and PyDev
– Komodo
– NetBeans IDE for Python
– PythonWin
– Wing, VisualStudio, etc..
Python Interpretation
• Lexical analysis
– Statements divided into group of tokens
– 5 types of tokens
• Delimiter(used for grouping, punctuation, assignment) eg.() [] {} , : ; “ ‘
• Literals(have fixed value)
• Identifier
• Operator
• keywords
• Syntax analysis
– Syntax defines the format or structure of statements and
sentences
• Semantic analysis
– Semantics defines the meaning of sentences and statements
Data types in Python
• Number
– Integer, float, long integer, complex
• String
• Boolean
• List
• Set
• Tuple
• Dictionary
Numeric Data Types
• int
This type is for whole numbers, positive or negative. Unlimited
length
– Examples: 23, -1756
>>> print(245673649874+2)
>>> 245673649876
>>> print(0b10) or (0B10) # binary
>>> 2
>>> print(0x20) # hex
>>> 32
• float
This type is for numbers with possible fraction parts.
Examples: 23.0, -14.561
>>> a = 1 #int
>>> l = 1000000L # Long
>>> e = 1.01325e5 # float
>>> f = 3.14159 # float
>>> c = 1+1 j # Complex
>>> print(f ∗c / a )
(3.14159+3.14159 j )
>>> printf(c.real, c.imag)
1.0 1.0
>>> abs ( c )
1.4142135623730951
del var1,var2,var3,...
Delete the reference to the number object using del.
• Complex numbers
>>>2+3j
2+3j
>>>(2+3j) * 5
10+15j
>>>2+3j * 5
2+15j
>>> (2+3j).real
2.0
>>> (2+3j).imag
3.0
>>> (2+3j).conjugate()
(2-3j)
• Boolean – True(1) / False(0)
>>>bool(1)
True
>>>bool(0)
False
>>>bool(‘1’) True
>>>bool(‘0’) True
>>>bool(‘hello’) True
>>>bool((1)) True
>>>bool((0)) False
>>>bool(()) False
>>>bool([]) False
>>>a=(1==True)
>>>b=(1==False)
>>>c=True+3
>>>d=False+7
>>>print(a) True
>>>print(b) False
>>>print(c) 4
>>>print(d) 7
>>> t = True
>>> f = not t
False
>>> f or t
True
>>> f and t
False
Operators in Python
• Arithmetic operators
• Comparison operators(conditional)
• Logical operators
• Assignment operators
• Bitwise operators
• Membership operators
• Identity operators
Arithmetic Operators
Arithmetic operators are used with numeric values to perform common
mathematical operations
The operations for integers are:
+ for addition
- for subtraction
* for multiplication
/ for integer division: The result of 14/5 is 2.8
// floor division 14 //5 = 2
% for remainder: The result of 14 % 5 is 4
** exponentiation
** take more precedence than * / % //
*, /, % take precedence over +, -
Eg. x + y * z will execute y*z first
Use parentheses to dictate order you want.
Eg. (x+y) * z will execute x+y first.
• When computing with floats, / will indicate
regular division with fractional results.
• Constants will have a decimal point.
• 14.0/5.0 will give 2.8
• 14/5 gives 2.8
Comparison Operators
Comparison operators are used to compare two
values
Operator Name Example
== Equal x == y
!= Not equal x != y
> Greater than x > y
< Less than x < y
>= Greater than or equal to x >= y
<= Less than or equal to x <= y
Logical Operators
Logical operators are used to combine conditional statements
Operator Description
and Returns True if both statements are true
Eg. x < 5 and x < 10
or Returns True if one of the statements is
true
Eg. x < 5 or x < 4
not Reverse the result, returns False if the result is
true
Eg. not(x < 5 and x < 10)
Bitwise Operators
Bitwise operators are used to compare (binary) numbers
Operator Name Description
& AND Sets each bit to 1 if both bits are 1
| OR Sets each bit to 1 if one of two bits is
1
^ XOR Sets each bit to 1 if only one of two
bits is 1
~ NOT Inverts all the bits
<< Zero fill left shift Shift left by pushing zeros in
from the right and let the
leftmost bits fall off
>> Signed right shift Shift right by pushing copies
of the leftmost bit in from
the left, and let the rightmost bits fall off
Bitwise Operators
Bitwise operators are used to compare (binary) numbers
Operator Name Description
& AND Sets each bit to 1 if both bits are 1
| OR Sets each bit to 1 if one of two bits is
1
^ XOR Sets each bit to 1 if only one of two
bits is 1
~ NOT Inverts all the bits
<< Zero fill left shift Shift left by pushing zeros in
from the right and let the
leftmost bits fall off
>> Signed right shift Shift right by pushing copies
of the leftmost bit in from
the left, and let the rightmost bits fall off
Assignment operators
Assignment operators are used to assign values to variables
Operator Example Same As
= x = 5 x = 5
+= x += 3 x = x + 3
-= x -= 3 x = x – 3
*= x *= 3 x = x * 3
/= x /= 3 x = x / 3
%= x %= 3 x = x % 3
//= x //= 3 x = x // 3
**= x **= 3 x = x ** 3
&= x &= 3 x = x & 3
|= x |= 3 x = x | 3
^= x ^= 3 x = x ^ 3
>>= x >>= 3 x = x >> 3
<<= x <<= 3 x = x << 3
Membership Operators
Membership operators are used to test if a sequence is
presented in an object
Operator Description
in Returns True if a sequence with the
specified value is present in the object
Eg. x in y
not in Returns True if a sequence with the
specified value is not present in the
object
Eg. x not in y
Identity Operators
Identity operators are used to compare the objects, not if they
are equal, but if they are actually the same object, with the
same memory location
Operator Description
is Returns True if both variables are the
same object
Eg. x is y
is not Returns True if both variables are not
the same object
Eg. x is not y
• Strings – continuous set of characters within ‘ ‘ or
“ “
• ‘hai’ same as “hai”
>>>print(“hello”)
hello
>>>print(“ “)
‘ ‘
>>>type(“hello”)
<class ‘str’>
>>> word = " h e l l o "
>>> 2∗word + " wo rld “
h e l l o h e l l o wo rld
>>> p ri n t (word [ 0 ] + word [ 2 ] + word[ −1])
h l o
>>> word [ 0 ] = ’H ’
>>>print(word)
Hello
>>> x , y = 1 , 1.234
>>> print(x,y)
1 1.234
• String special operators:
+ concatenation
* repetition
[ ] give character at index
[ : ] range of characters
in – membership (return true if char exist in string)
not in - membership (return true if char not exist in
string)
str = 'Hello World!'
print(str)
print(str[0])
print(str[2:5])
print(str[2:])
print(str * 2)
print(str + "TEST")
• Output:
Hello World!
H
llo
llo World!
Hello World!Hello World!
Hello World!TEST
str = 'HelloWorld'
print(str)
print(str[-1])
print(str[1:6])
print(str[2:-3])
print(str[ :-7])
print(str[-3: ])
print(str[: : -1])
Output
HelloWorld
d
elloW
lloWo
Hel
rld
dlroWolleH
String methods
• capitalize()
• title()
• endswith(suffix,beg=0,end=len(string))
• find(string, beg=0,end=len(string))
• isalnum()
• isdigit()
• islower()
• isspace()
• istitle()
• isupper()
• join()
• len()
• lower()
• upper()
• lstrip()
• max()
• min()
• replace()
• rstrip()
• split()
• swapcase()
String Methods
• Assign a string to a
variable
• In this case “hw”
• hw.title()
• hw.upper()
• hw.isdigit()
• hw.islower()
49
String Methods
• The string held in your variable remains the
same
• The method returns an altered string
• Changing the variable requires reassignment
– hw = hw.upper()
– hw now equals “HELLO WORLD”
50
join() method is a string method and returns a
string in which the elements of the sequence
have been joined by the str separator
Eg.
list1 = ['1','2','3','4']
s = "-"
s.join(list1)
1-2-3-4
split() - split a string into a list where each word
is a list item
Eg.
txt = "welcome to the jungle“
x = txt.split()
print(x)
['welcome', 'to', 'the', 'jungle']
>>> a = ’ h e l l o wo rld ’
>>> a . s t a r t s w i t h ( ’ h e l l ’ )
True
>>> a . endswith ( ’ l d ’ )
True
>>> a . upper ( )
’HELLO WORLD’
>>> a . upper ( ) . lower ( )
’ h e l l o wo rld ’
>>> a . s p l i t ( )
[ ’ h e l l o ’ , ’ wo rld ’ ]
>>> ’ ’ . j o i n ( [ ’ a ’ , ’ b ’ , ’ c ’ ] )
’ a b c ’
>>> x , y = 1 , 1.234
>>>”x=%s” %x
x=1
Runtime user Input
• To get input from the user, we use an assignment
statement of the form
<variable> = input(<prompt>)
it always treat the input value as string.
• Here
– <prompt> would be replaced by a prompt for the user
inside quotation marks
– If there is no prompt, the parentheses are still needed
• Semantics
– The prompt will be displayed
– User enters number
– Value entered is stored as the value of the variable
• To get int or float input from the user, we use
typecasting before input statement of the
form
<variable> = (int)input(<prompt>)
it will treat the input value as int.
<variable> = (float)input(<prompt>)
it will treat the input value as float.
Print Statement
• For output we use statements of the form
print <expression>
• Semantics
– Value of expression is computed
– This value is displayed
• Several expressions can be printed – separate them by
commas
• Eg.
a,b=2,3.5
print(a+b, b*a)
5.5 7.0
Example - Fahrenheit to Centigrade
• We want to convert a Fahrenheit
temperature to Centigrade.
• The formula is C = (F -32) x 5/9
• We use type float for the temperatures.
Python Session
List
l1=[1,2.5,3.14,”hello”]
l2=[4.8,”cse”]
print(l1)
print(l1[0])
print(l1[1:3])
print(l1[1: ])
print(l1+l2)
print(l1*3)
print(l2*2)
l1[2]=3.5
print(l1)
[1, 2.5, 3.5, “hello”]
Tuples
List:
List items are enclosed within [ ]
Lists can be updated
Tuple:
Tuple items are enclosed within ( )
Tuples can’t be updated
Tuples can be thought of readonly list
Tuples
l1=(1,2.5,3.14,”hello”)
l2=(4.8,”cse”)
print(l1)
print(l1[0])
print(l1[1:3])
print(l1[1: ])
print(l1+l2)
print(l1*3)
print(l2*2)
>>>l1[1]=3.0
Invalid Syntax Error
Set
• Sets are used to store multiple items in a single
variable.
• Set items can not be updated, but items can be
removed or added.
• Sets are written with curly brackets.
• Not allow duplicate items
• Items can’t be referred by index or key
• Eg. s1={1,1,1,2,2,2,3,3,4,5,5,5,5,5}
print(s1)
{1,2,3,4,5}
Dictionary
• Similar to associative arrays or hashes in perl
• Key value pairs
• Key=almost any data type(number or string)
• Value=any arbitrary python object
• Nested dictionaries
– Define dictionary inside another dictionary
– Eg. d={"id":101, "name":"AAA", "dept":"QA“,
“addr”:{‘street’:’new colony 2nd cross street’,
‘town’:’porur’, ‘city’:’chennai’, ‘pincode’:600116} }
Dic.py
d={"id":101, "name":"AAA", "dept":"QA"}
print(d)
print("Emp ID=",d['id'])
print("Emp Name=",d['name'])
print("Emp Dept=",d['dept'])
d['dept']="RA"
print("Changed Emp Dept=",d['dept'])
d['score']=95
print(d)
d.pop('dept')
print("After Pop:")
print(d)
print(d['dept'])
output
{'id': 101, 'name': 'AAA', 'dept': 'QA'}
Emp ID= 101
Emp Name= AAA
Emp Dept= QA
Changed Emp Dept= RA
{'id': 101, 'name': 'AAA', 'dept': 'RA', 'score': 95}
After Pop:
{'id': 101, 'name': 'AAA', 'score': 95}
Traceback (most recent call last):
File "C:/Users/Admin/AppData/Local/Programs/Python/Python37-32/dic.py", line 13,
in <module>
print(d['dept'])
KeyError: 'dept'
Conditional statements
• 3 types of statements in python
– Selection/conditional
– Iteration
– Jump
• Selection/conditional statements
– If
– If else
– If elif else
• if <condn>:
<then statements>
• Eg.
• if x<0:
print(“x is negative”)
• if <condn>:
<then statements>
else:
<else statements>
Eg:
if x%2 ==0:
print(“Even”)
else:
print(“Odd”)
Nested if
If elif else
If <condn1>:
<statements>
elif <condn2>:
<statements>
elif <condn3>:
<statements>
else:
<statements>
if<condn1>:
<statements>
else:
if<condn2>:
<statements>
else:
<statements>
Eg.
m=85
if m>90 and m<=100 :
print(“1st class”)
elif m>80 and m<=90 :
print(“2nd class”)
elif m>70 and m<=80 :
print(“3rd class”)
elif m>60 and m<=70 :
print(“4th class”)
elif m>50 and m<=60 :
print(“5th class”)
else:
print(“FAIL”)
Iteration/Loop statements
• for
• while
for:
for <variable> in <sequence> :
<body of loop>
Eg.
Printing 1 to 10
for i in range(1,11):
print(i)
Printing odd numbers from 1 to 100
for i in range(1,101):
if(i%2 != 0):
print(i)
while:
while <condn>:
<statements>
else:
<statements>
Eg.
a=0,b=10
while a<b :
print(a)
a=a+1
Output:
0
1
2
3
4
5
6
7
8
9
Eg. Sum of n natural numbers
n = int(input("Enter n: "))
sum = 0, i = 1
while i <= n:
sum = sum + i
i = i+1
print("The sum is", sum)
Output:
Enter n: 10
The sum is 55
Functions
– builtin functions
– User defined functions
• Defining function:
– Begin with def followed by function name and ()
– Input parameters / arguments within () and
followed by : at end
– Function body (code block) is intended
– Return [expr]
• eg:
s=“John”
def printstr(s):
“Welcome to Python”
print(s)
return
• Eg;
def add(a,b):
return a+b
>>>r=add(5,6)
print(r)
11
Eg. Fibonancci series generation
n=int(input(“enter limit”))
def fib(n):
a,b=0,1
while a<n:
print(a)
a=b
b=a+b
print()
Eg. Fibnonaaci series
return a list of numbers from function
def fib(n):
r=[]
a,b=0,1
while a<n:
r.append(a)
a=b
b=a+b
return r
L=fib(10)
print(L)
0 1 1 2 3 5 8
• 4 types of arguments
– Position arguments
– Keyword arguments
– Default arguments
– Variable length arguments
• Positional arguments
Eg.
def add(a,b):
c=a+b
print(c)
add(5,6)
Eg.
def person(name, age):
print(“Name=“, name)
print(“Age=“, age)
person(‘John’, 28)
• Keyword arguments
Eg.
def person(name, age):
print(“Name=“, name)
print(“Age=“, age)
person(age=28, name=‘John’)
• Default arguments
Eg.
def person(name, age=18):
print(“Name=“, name)
print(“Age=“, age)
person(‘John’)
person(‘Karan’,25)
Eg.
def area(pi=3.14, r=2):
res=pi*r*r
print(res)
area()
area(r=5)
Eg.
def greeting(name, msg=“welcome”)
print(“Hello”, name, msg)
greeting(“John”)
greeting(“John”, “Good morning”)
• Variable length arguments
– When we need to process function for more
arguments than defined in function – variable
length arguments used
– * placed in front of all non keyword variable
length arguments
– This tuple remains empty when no additional
arguments specified during function call
Eg.
def sum(a,*b):
print(a)
print(b)
c=a
for i in b:
c=c+i
print(c)
sum(5,6)
sum(5,6,14,25,37)
Eg.
def sum(*b):
print(b)
c=0
for i in b:
c=c+i
print(c)
Sum(5)
sum(5,6)
sum(5,6,14,25,37)
Keyworded variable length arguments
Eg.
def person(name, **data):
print(name)
for i , j in data.items() :
print(i,j)
person(‘Navin’, age=28, city=‘Mumbai’, mobile=9840374322)
o/p:
Navin
age 28
city Mumbai
mobile 9840374322
Pass by value
Eg.
def update(x):
x=8
print(“x=“, x)
a=10
update(a)
print(“a=“,a)
o/p:
x=8
a=10
• In python no pass by value or pass by
reference
• In python everything are objects
• id() returns object id or memory
reference(memory location id)
Eg.
def update(x):
print(id(x))
x=8
print(id(x))
print(“x=“, x)
a=10
print(id(a))
update(a)
print(“a=“,a)
o/p:
17954309824
17954309824
17954309862
x=8
a=10
Eg.
def update(l):
print(id(l)
l[1]=25
print(id(l))
print(“l=“, l)
l=[10,20,30]
print(id(l))
update(l)
print(“l=“,l)
o/p:
17954309824
17954309824
17954309824
l=[10,25,30]
l=[10,25,30]
Jump statements
Break
Continue
Pass
Loop else block
break
Jump out of the closest loop
Eg.
max=10
x=int(input(“enter a number”))
i=1
while i<=x:
if i>max:
print(“crossed max limit”)
break
print(“Hello”)
i=i+1
print(“Bye”)
continue
Used to skip an iteration of the loop when a
condition is met
Eg.
for i in range(1, 101):
if i%3 == 0 :
continue
print(i)
print(“Bye”)
O/p:
1,2,4,5,7,8,10,11,13,14,16,17,……….
For i in range(1, 101):
if(i%3 == 0 or i%5 == 0):
continue
print(i)
print(“Bye”)
O/p:
1,2,4,7,8,11,13,14,16,17,……………….
pass
No-operation, placeholder used when syntax requires
statement but we don’t have nothing useful to execute.
Eg.
i=1
while i<=10 :
if i==6 :
print(“skip : simply pass”)
pass
else:
print(i)
i=i+1
o/p:
1
2
3
4
5
skip : simply pass
7
8
9
10
Loop else
• else block associated with loop
Eg.
l=[11,33,52,39,66,75,37,21,24,44,13]
for i in l:
if i%2 == 0 :
print(“Divisible by 5: “, i)
break
else:
print(“Not found”)
Global variables
Eg.
a=10
def func():
a=15
print(“inside function “, a)
func()
print(“outside function”, a)
o/p:
inside function 15
outside function 10
Eg.
a=10
def func():
global a
a=15
print(“inside function “, a)
func()
print(“outside function”, a)
o/p:
inside function 15
outside function 15
Eg.
a=10
print(id(a))
def func():
a=15
x=globals()[‘a’]
print(id(x))
print(“inside function “, a)
globals()[‘a’]=20
func()
print(“outside function”, a)
o/p:
265959824
265959824
inside function 15
outside function 20
Lambda expressions
• Functions without name – anonymous function
• lambda function or lambda expressions is a small anonymous
function
• Can take any no. of arguments but only one expression allowed
• Functions are objects in python
Syntax:
lambda arguments : expr
Eg.
x=lambda a: a+10
print(x(5))
O/p:
15
• multiply argument a with b and return result
Eg.
x=lambda a,b : a*b
print(x(5,6))
o/p:
30
Eg.
f=lambda a : a*a
result=f(5)
print(result)
• The power of lambda is better when we use them
as an anonymous function inside another
function
Eg.
def func(n):
return lambda a : a*n
r=func(2)
print(r(11))
o/p:
22
Eg.
def func(n):
return lambda a : a*n
r1=func(2)
r2=func(3)
print(r1(11))
print(r2(11))
o/p:
22
33
filter
Eg.
def is_even(n):
return n%2 == 0
num=[11,33,52,39,66,75,37,21,24,44,13]
even=list(filter(is_even, num))
print(even)
Eg.
num=[11,33,52,39,66,75,37,21,24,44,13]
even=list(filter(lambda n: n%2==0, num))
print(even)
map
Eg.
def update(n):
return 2*n
num=[11,33,52,39,66,75,37,21,24,44,13]
even=list(filter(lambda n: n%2==0, num))
double=list(map(update, even))
print(double)
Eg.
num=[11,33,52,39,66,75,37,21,24,44,13]
even=list(filter(lambda n: n%2==0, num))
double=list(map(lambda n : 2*n, even))
print(double)
reduce
Eg.
from functools import reduce
def add_all(a,b):
return a+b
num=[11,33,52,39,66,75,37,21,24,44,13]
even=list(filter(lambda n: n%2==0, num))
double=list(map(lambda n : 2*n, even))
print(double)
sum=reduce(add_all, double)
print(sum)
Eg.
from functools import reduce
num=[11,33,52,39,66,75,37,21,24,44,13]
even=list(filter(lambda n: n%2==0, num))
double=list(map(lambda n : 2*n, even))
print(double)
sum=reduce(lambda a,b : a+b, double)
print(sum)
• Use lambda function when anonymous
function is required for a short period of time
• Lambda function does not need a name
during function definition
• Lambda functions can be used along with
built-in functions such as map(), filter() and
reduce()
• Guidelines to use lambda function/expr:
– If function can’t able to be expressed in one line,
don’t use lambda
– If function call uses several lambda expressions,
difficult to understand code(not recommended)
– If same function is used in many places, better to
use normal function rather than lambda

More Related Content

What's hot (20)

Learn Python The Hard Way Presentation
Learn Python The Hard Way PresentationLearn Python The Hard Way Presentation
Learn Python The Hard Way Presentation
Amira ElSharkawy
 
Python
PythonPython
Python
Rural Engineering College Hulkoti
 
Python-01| Fundamentals
Python-01| FundamentalsPython-01| Fundamentals
Python-01| Fundamentals
Mohd Sajjad
 
Python 3 Programming Language
Python 3 Programming LanguagePython 3 Programming Language
Python 3 Programming Language
Tahani Al-Manie
 
PYTHON -Chapter 2 - Functions, Exception, Modules and Files -MAULIK BOR...
PYTHON -Chapter 2 - Functions,   Exception, Modules  and    Files -MAULIK BOR...PYTHON -Chapter 2 - Functions,   Exception, Modules  and    Files -MAULIK BOR...
PYTHON -Chapter 2 - Functions, Exception, Modules and Files -MAULIK BOR...
Maulik Borsaniya
 
Python ppt
Python pptPython ppt
Python ppt
Anush verma
 
Introduction to the basics of Python programming (part 1)
Introduction to the basics of Python programming (part 1)Introduction to the basics of Python programming (part 1)
Introduction to the basics of Python programming (part 1)
Pedro Rodrigues
 
Python Seminar PPT
Python Seminar PPTPython Seminar PPT
Python Seminar PPT
Shivam Gupta
 
PPT on Data Science Using Python
PPT on Data Science Using PythonPPT on Data Science Using Python
PPT on Data Science Using Python
NishantKumar1179
 
Python Presentation
Python PresentationPython Presentation
Python Presentation
Narendra Sisodiya
 
Python language data types
Python language data typesPython language data types
Python language data types
Hoang Nguyen
 
Intro to Python Programming Language
Intro to Python Programming LanguageIntro to Python Programming Language
Intro to Python Programming Language
Dipankar Achinta
 
Overview of python 2019
Overview of python 2019Overview of python 2019
Overview of python 2019
Samir Mohanty
 
Let’s Learn Python An introduction to Python
Let’s Learn Python An introduction to Python Let’s Learn Python An introduction to Python
Let’s Learn Python An introduction to Python
Jaganadh Gopinadhan
 
Programming with Python
Programming with PythonProgramming with Python
Programming with Python
Rasan Samarasinghe
 
Python Basics
Python Basics Python Basics
Python Basics
Adheetha O. V
 
Python Basics by Akanksha Bali
Python Basics by Akanksha BaliPython Basics by Akanksha Bali
Python Basics by Akanksha Bali
Akanksha Bali
 
Python revision tour i
Python revision tour iPython revision tour i
Python revision tour i
Mr. Vikram Singh Slathia
 
Python Basics
Python BasicsPython Basics
Python Basics
tusharpanda88
 
Introduction to Python programming Language
Introduction to Python programming LanguageIntroduction to Python programming Language
Introduction to Python programming Language
MansiSuthar3
 
Learn Python The Hard Way Presentation
Learn Python The Hard Way PresentationLearn Python The Hard Way Presentation
Learn Python The Hard Way Presentation
Amira ElSharkawy
 
Python-01| Fundamentals
Python-01| FundamentalsPython-01| Fundamentals
Python-01| Fundamentals
Mohd Sajjad
 
Python 3 Programming Language
Python 3 Programming LanguagePython 3 Programming Language
Python 3 Programming Language
Tahani Al-Manie
 
PYTHON -Chapter 2 - Functions, Exception, Modules and Files -MAULIK BOR...
PYTHON -Chapter 2 - Functions,   Exception, Modules  and    Files -MAULIK BOR...PYTHON -Chapter 2 - Functions,   Exception, Modules  and    Files -MAULIK BOR...
PYTHON -Chapter 2 - Functions, Exception, Modules and Files -MAULIK BOR...
Maulik Borsaniya
 
Introduction to the basics of Python programming (part 1)
Introduction to the basics of Python programming (part 1)Introduction to the basics of Python programming (part 1)
Introduction to the basics of Python programming (part 1)
Pedro Rodrigues
 
Python Seminar PPT
Python Seminar PPTPython Seminar PPT
Python Seminar PPT
Shivam Gupta
 
PPT on Data Science Using Python
PPT on Data Science Using PythonPPT on Data Science Using Python
PPT on Data Science Using Python
NishantKumar1179
 
Python language data types
Python language data typesPython language data types
Python language data types
Hoang Nguyen
 
Intro to Python Programming Language
Intro to Python Programming LanguageIntro to Python Programming Language
Intro to Python Programming Language
Dipankar Achinta
 
Overview of python 2019
Overview of python 2019Overview of python 2019
Overview of python 2019
Samir Mohanty
 
Let’s Learn Python An introduction to Python
Let’s Learn Python An introduction to Python Let’s Learn Python An introduction to Python
Let’s Learn Python An introduction to Python
Jaganadh Gopinadhan
 
Python Basics by Akanksha Bali
Python Basics by Akanksha BaliPython Basics by Akanksha Bali
Python Basics by Akanksha Bali
Akanksha Bali
 
Introduction to Python programming Language
Introduction to Python programming LanguageIntroduction to Python programming Language
Introduction to Python programming Language
MansiSuthar3
 

Similar to Python programming (20)

Basic concept of Python.pptx includes design tool, identifier, variables.
Basic concept of Python.pptx includes design tool, identifier, variables.Basic concept of Python.pptx includes design tool, identifier, variables.
Basic concept of Python.pptx includes design tool, identifier, variables.
supriyasarkar38
 
Tutorial on-python-programming
Tutorial on-python-programmingTutorial on-python-programming
Tutorial on-python-programming
Chetan Giridhar
 
Python_Haegl.powerpoint presentation. tx
Python_Haegl.powerpoint presentation. txPython_Haegl.powerpoint presentation. tx
Python_Haegl.powerpoint presentation. tx
vishwanathgoudapatil1
 
Advance Python programming languages-Simple Easy learning
Advance Python programming languages-Simple Easy learningAdvance Python programming languages-Simple Easy learning
Advance Python programming languages-Simple Easy learning
sherinjoyson
 
intro to python.pptx
intro to python.pptxintro to python.pptx
intro to python.pptx
UpasnaSharma37
 
Lecture1_introduction to python.pptx
Lecture1_introduction to python.pptxLecture1_introduction to python.pptx
Lecture1_introduction to python.pptx
MohammedAlYemeni1
 
01-Python-Basics.ppt
01-Python-Basics.ppt01-Python-Basics.ppt
01-Python-Basics.ppt
VicVic56
 
Intro-to-Python-Part-1-first-part-edition.pdf
Intro-to-Python-Part-1-first-part-edition.pdfIntro-to-Python-Part-1-first-part-edition.pdf
Intro-to-Python-Part-1-first-part-edition.pdf
ssuser543728
 
Python introduction towards data science
Python introduction towards data sciencePython introduction towards data science
Python introduction towards data science
deepak teja
 
Welcome to python workshop
Welcome to python workshopWelcome to python workshop
Welcome to python workshop
Mukul Kirti Verma
 
Python Programming Basic , introductions
Python Programming Basic , introductionsPython Programming Basic , introductions
Python Programming Basic , introductions
M.H.Saboo Siddik Polytechnic
 
Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...
Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...
Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...
DRVaibhavmeshram1
 
17575602.ppt
17575602.ppt17575602.ppt
17575602.ppt
TejaValmiki
 
Python Programming Introduction demo.ppt
Python Programming Introduction demo.pptPython Programming Introduction demo.ppt
Python Programming Introduction demo.ppt
JohariNawab
 
web programming UNIT VIII python by Bhavsingh Maloth
web programming UNIT VIII python by Bhavsingh Malothweb programming UNIT VIII python by Bhavsingh Maloth
web programming UNIT VIII python by Bhavsingh Maloth
Bhavsingh Maloth
 
Sessisgytcfgggggggggggggggggggggggggggggggg
SessisgytcfggggggggggggggggggggggggggggggggSessisgytcfgggggggggggggggggggggggggggggggg
Sessisgytcfgggggggggggggggggggggggggggggggg
pawankamal3
 
Python
PythonPython
Python
Kumar Gaurav
 
Python lab basics
Python lab basicsPython lab basics
Python lab basics
Abi_Kasi
 
Python
PythonPython
Python
Aashish Jain
 
BASICS OF PYTHON usefull for the student who would like to learn on their own
BASICS OF PYTHON usefull for the student who would like to learn on their ownBASICS OF PYTHON usefull for the student who would like to learn on their own
BASICS OF PYTHON usefull for the student who would like to learn on their own
Nandini485510
 
Basic concept of Python.pptx includes design tool, identifier, variables.
Basic concept of Python.pptx includes design tool, identifier, variables.Basic concept of Python.pptx includes design tool, identifier, variables.
Basic concept of Python.pptx includes design tool, identifier, variables.
supriyasarkar38
 
Tutorial on-python-programming
Tutorial on-python-programmingTutorial on-python-programming
Tutorial on-python-programming
Chetan Giridhar
 
Python_Haegl.powerpoint presentation. tx
Python_Haegl.powerpoint presentation. txPython_Haegl.powerpoint presentation. tx
Python_Haegl.powerpoint presentation. tx
vishwanathgoudapatil1
 
Advance Python programming languages-Simple Easy learning
Advance Python programming languages-Simple Easy learningAdvance Python programming languages-Simple Easy learning
Advance Python programming languages-Simple Easy learning
sherinjoyson
 
Lecture1_introduction to python.pptx
Lecture1_introduction to python.pptxLecture1_introduction to python.pptx
Lecture1_introduction to python.pptx
MohammedAlYemeni1
 
01-Python-Basics.ppt
01-Python-Basics.ppt01-Python-Basics.ppt
01-Python-Basics.ppt
VicVic56
 
Intro-to-Python-Part-1-first-part-edition.pdf
Intro-to-Python-Part-1-first-part-edition.pdfIntro-to-Python-Part-1-first-part-edition.pdf
Intro-to-Python-Part-1-first-part-edition.pdf
ssuser543728
 
Python introduction towards data science
Python introduction towards data sciencePython introduction towards data science
Python introduction towards data science
deepak teja
 
Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...
Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...
Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...
DRVaibhavmeshram1
 
Python Programming Introduction demo.ppt
Python Programming Introduction demo.pptPython Programming Introduction demo.ppt
Python Programming Introduction demo.ppt
JohariNawab
 
web programming UNIT VIII python by Bhavsingh Maloth
web programming UNIT VIII python by Bhavsingh Malothweb programming UNIT VIII python by Bhavsingh Maloth
web programming UNIT VIII python by Bhavsingh Maloth
Bhavsingh Maloth
 
Sessisgytcfgggggggggggggggggggggggggggggggg
SessisgytcfggggggggggggggggggggggggggggggggSessisgytcfgggggggggggggggggggggggggggggggg
Sessisgytcfgggggggggggggggggggggggggggggggg
pawankamal3
 
Python lab basics
Python lab basicsPython lab basics
Python lab basics
Abi_Kasi
 
BASICS OF PYTHON usefull for the student who would like to learn on their own
BASICS OF PYTHON usefull for the student who would like to learn on their ownBASICS OF PYTHON usefull for the student who would like to learn on their own
BASICS OF PYTHON usefull for the student who would like to learn on their own
Nandini485510
 
Ad

Recently uploaded (20)

Research_Sensitization_&_Innovative_Project_Development.pptx
Research_Sensitization_&_Innovative_Project_Development.pptxResearch_Sensitization_&_Innovative_Project_Development.pptx
Research_Sensitization_&_Innovative_Project_Development.pptx
niranjancse
 
Computer_vision-photometric_image_formation.pdf
Computer_vision-photometric_image_formation.pdfComputer_vision-photometric_image_formation.pdf
Computer_vision-photometric_image_formation.pdf
kumarprem6767merp
 
SEW make Brake BE05 – BE30 Brake – Repair Kit
SEW make Brake BE05 – BE30 Brake – Repair KitSEW make Brake BE05 – BE30 Brake – Repair Kit
SEW make Brake BE05 – BE30 Brake – Repair Kit
projectultramechanix
 
362 Alec Data Center Solutions-Slysium Data Center-AUH-ABB Furse.pdf
362 Alec Data Center Solutions-Slysium Data Center-AUH-ABB Furse.pdf362 Alec Data Center Solutions-Slysium Data Center-AUH-ABB Furse.pdf
362 Alec Data Center Solutions-Slysium Data Center-AUH-ABB Furse.pdf
djiceramil
 
Pavement and its types, Application of rigid and Flexible Pavements
Pavement and its types, Application of rigid and Flexible PavementsPavement and its types, Application of rigid and Flexible Pavements
Pavement and its types, Application of rigid and Flexible Pavements
Sakthivel M
 
Top Cite Articles- International Journal on Soft Computing, Artificial Intell...
Top Cite Articles- International Journal on Soft Computing, Artificial Intell...Top Cite Articles- International Journal on Soft Computing, Artificial Intell...
Top Cite Articles- International Journal on Soft Computing, Artificial Intell...
ijscai
 
A DECISION SUPPORT SYSTEM FOR ESTIMATING COST OF SOFTWARE PROJECTS USING A HY...
A DECISION SUPPORT SYSTEM FOR ESTIMATING COST OF SOFTWARE PROJECTS USING A HY...A DECISION SUPPORT SYSTEM FOR ESTIMATING COST OF SOFTWARE PROJECTS USING A HY...
A DECISION SUPPORT SYSTEM FOR ESTIMATING COST OF SOFTWARE PROJECTS USING A HY...
ijfcstjournal
 
ACEP Magazine Fifth Edition on 5june2025
ACEP Magazine Fifth Edition on 5june2025ACEP Magazine Fifth Edition on 5june2025
ACEP Magazine Fifth Edition on 5june2025
Rahul
 
The first edition of the AIAG-VDA FMEA.pptx
The first edition of the AIAG-VDA FMEA.pptxThe first edition of the AIAG-VDA FMEA.pptx
The first edition of the AIAG-VDA FMEA.pptx
Mayank Mathur
 
Universal Human Values and professional ethics Quantum AKTU BVE401
Universal Human Values and professional ethics Quantum AKTU BVE401Universal Human Values and professional ethics Quantum AKTU BVE401
Universal Human Values and professional ethics Quantum AKTU BVE401
Unknown
 
Rearchitecturing a 9-year-old legacy Laravel application.pdf
Rearchitecturing a 9-year-old legacy Laravel application.pdfRearchitecturing a 9-year-old legacy Laravel application.pdf
Rearchitecturing a 9-year-old legacy Laravel application.pdf
Takumi Amitani
 
fHUINhKG5lM1WBBk608.pptxfhjjhhjffhiuhhghj
fHUINhKG5lM1WBBk608.pptxfhjjhhjffhiuhhghjfHUINhKG5lM1WBBk608.pptxfhjjhhjffhiuhhghj
fHUINhKG5lM1WBBk608.pptxfhjjhhjffhiuhhghj
yadavshivank2006
 
chemistry investigatory project for class 12
chemistry investigatory project for class 12chemistry investigatory project for class 12
chemistry investigatory project for class 12
Susis10
 
operationg systemsdocumentmemorymanagement
operationg systemsdocumentmemorymanagementoperationg systemsdocumentmemorymanagement
operationg systemsdocumentmemorymanagement
SNIGDHAAPPANABHOTLA
 
02 - Ethics & Professionalism - BEM, IEM, MySET.PPT
02 - Ethics & Professionalism - BEM, IEM, MySET.PPT02 - Ethics & Professionalism - BEM, IEM, MySET.PPT
02 - Ethics & Professionalism - BEM, IEM, MySET.PPT
SharinAbGhani1
 
Rigor, ethics, wellbeing and resilience in the ICT doctoral journey
Rigor, ethics, wellbeing and resilience in the ICT doctoral journeyRigor, ethics, wellbeing and resilience in the ICT doctoral journey
Rigor, ethics, wellbeing and resilience in the ICT doctoral journey
Yannis
 
11th International Conference on Data Mining (DaMi 2025)
11th International Conference on Data Mining (DaMi 2025)11th International Conference on Data Mining (DaMi 2025)
11th International Conference on Data Mining (DaMi 2025)
kjim477n
 
Third Review PPT that consists of the project d etails like abstract.
Third Review PPT that consists of the project d etails like abstract.Third Review PPT that consists of the project d etails like abstract.
Third Review PPT that consists of the project d etails like abstract.
Sowndarya6
 
3. What is the principles of Teamwork_Module_V1.0.ppt
3. What is the principles of Teamwork_Module_V1.0.ppt3. What is the principles of Teamwork_Module_V1.0.ppt
3. What is the principles of Teamwork_Module_V1.0.ppt
engaash9
 
Tree_Traversals.pptbbbbbbbbbbbbbbbbbbbbbbbbb
Tree_Traversals.pptbbbbbbbbbbbbbbbbbbbbbbbbbTree_Traversals.pptbbbbbbbbbbbbbbbbbbbbbbbbb
Tree_Traversals.pptbbbbbbbbbbbbbbbbbbbbbbbbb
RATNANITINPATIL
 
Research_Sensitization_&_Innovative_Project_Development.pptx
Research_Sensitization_&_Innovative_Project_Development.pptxResearch_Sensitization_&_Innovative_Project_Development.pptx
Research_Sensitization_&_Innovative_Project_Development.pptx
niranjancse
 
Computer_vision-photometric_image_formation.pdf
Computer_vision-photometric_image_formation.pdfComputer_vision-photometric_image_formation.pdf
Computer_vision-photometric_image_formation.pdf
kumarprem6767merp
 
SEW make Brake BE05 – BE30 Brake – Repair Kit
SEW make Brake BE05 – BE30 Brake – Repair KitSEW make Brake BE05 – BE30 Brake – Repair Kit
SEW make Brake BE05 – BE30 Brake – Repair Kit
projectultramechanix
 
362 Alec Data Center Solutions-Slysium Data Center-AUH-ABB Furse.pdf
362 Alec Data Center Solutions-Slysium Data Center-AUH-ABB Furse.pdf362 Alec Data Center Solutions-Slysium Data Center-AUH-ABB Furse.pdf
362 Alec Data Center Solutions-Slysium Data Center-AUH-ABB Furse.pdf
djiceramil
 
Pavement and its types, Application of rigid and Flexible Pavements
Pavement and its types, Application of rigid and Flexible PavementsPavement and its types, Application of rigid and Flexible Pavements
Pavement and its types, Application of rigid and Flexible Pavements
Sakthivel M
 
Top Cite Articles- International Journal on Soft Computing, Artificial Intell...
Top Cite Articles- International Journal on Soft Computing, Artificial Intell...Top Cite Articles- International Journal on Soft Computing, Artificial Intell...
Top Cite Articles- International Journal on Soft Computing, Artificial Intell...
ijscai
 
A DECISION SUPPORT SYSTEM FOR ESTIMATING COST OF SOFTWARE PROJECTS USING A HY...
A DECISION SUPPORT SYSTEM FOR ESTIMATING COST OF SOFTWARE PROJECTS USING A HY...A DECISION SUPPORT SYSTEM FOR ESTIMATING COST OF SOFTWARE PROJECTS USING A HY...
A DECISION SUPPORT SYSTEM FOR ESTIMATING COST OF SOFTWARE PROJECTS USING A HY...
ijfcstjournal
 
ACEP Magazine Fifth Edition on 5june2025
ACEP Magazine Fifth Edition on 5june2025ACEP Magazine Fifth Edition on 5june2025
ACEP Magazine Fifth Edition on 5june2025
Rahul
 
The first edition of the AIAG-VDA FMEA.pptx
The first edition of the AIAG-VDA FMEA.pptxThe first edition of the AIAG-VDA FMEA.pptx
The first edition of the AIAG-VDA FMEA.pptx
Mayank Mathur
 
Universal Human Values and professional ethics Quantum AKTU BVE401
Universal Human Values and professional ethics Quantum AKTU BVE401Universal Human Values and professional ethics Quantum AKTU BVE401
Universal Human Values and professional ethics Quantum AKTU BVE401
Unknown
 
Rearchitecturing a 9-year-old legacy Laravel application.pdf
Rearchitecturing a 9-year-old legacy Laravel application.pdfRearchitecturing a 9-year-old legacy Laravel application.pdf
Rearchitecturing a 9-year-old legacy Laravel application.pdf
Takumi Amitani
 
fHUINhKG5lM1WBBk608.pptxfhjjhhjffhiuhhghj
fHUINhKG5lM1WBBk608.pptxfhjjhhjffhiuhhghjfHUINhKG5lM1WBBk608.pptxfhjjhhjffhiuhhghj
fHUINhKG5lM1WBBk608.pptxfhjjhhjffhiuhhghj
yadavshivank2006
 
chemistry investigatory project for class 12
chemistry investigatory project for class 12chemistry investigatory project for class 12
chemistry investigatory project for class 12
Susis10
 
operationg systemsdocumentmemorymanagement
operationg systemsdocumentmemorymanagementoperationg systemsdocumentmemorymanagement
operationg systemsdocumentmemorymanagement
SNIGDHAAPPANABHOTLA
 
02 - Ethics & Professionalism - BEM, IEM, MySET.PPT
02 - Ethics & Professionalism - BEM, IEM, MySET.PPT02 - Ethics & Professionalism - BEM, IEM, MySET.PPT
02 - Ethics & Professionalism - BEM, IEM, MySET.PPT
SharinAbGhani1
 
Rigor, ethics, wellbeing and resilience in the ICT doctoral journey
Rigor, ethics, wellbeing and resilience in the ICT doctoral journeyRigor, ethics, wellbeing and resilience in the ICT doctoral journey
Rigor, ethics, wellbeing and resilience in the ICT doctoral journey
Yannis
 
11th International Conference on Data Mining (DaMi 2025)
11th International Conference on Data Mining (DaMi 2025)11th International Conference on Data Mining (DaMi 2025)
11th International Conference on Data Mining (DaMi 2025)
kjim477n
 
Third Review PPT that consists of the project d etails like abstract.
Third Review PPT that consists of the project d etails like abstract.Third Review PPT that consists of the project d etails like abstract.
Third Review PPT that consists of the project d etails like abstract.
Sowndarya6
 
3. What is the principles of Teamwork_Module_V1.0.ppt
3. What is the principles of Teamwork_Module_V1.0.ppt3. What is the principles of Teamwork_Module_V1.0.ppt
3. What is the principles of Teamwork_Module_V1.0.ppt
engaash9
 
Tree_Traversals.pptbbbbbbbbbbbbbbbbbbbbbbbbb
Tree_Traversals.pptbbbbbbbbbbbbbbbbbbbbbbbbbTree_Traversals.pptbbbbbbbbbbbbbbbbbbbbbbbbb
Tree_Traversals.pptbbbbbbbbbbbbbbbbbbbbbbbbb
RATNANITINPATIL
 
Ad

Python programming

  • 1. PYTHON PROGRAMMING - INTRODUCTION, DATA TYPES, OPERATORS, CONTROL FLOW STATEMENTS, FUNCTIONS & LAMBDA EXPRESSIONS Ms. V.SAROJA Assistant Professor Department of Computer Science and Engineering SRM Institute of Science and Technology, Chennai
  • 2. INTRODUCTION • General purpose programming language • Object oriented • Programming + scripting language • Interactive • Interpreted • High level programming • Open source • Powerful – Dynamic typing – Builtin types and tools – Library utilities – Third party utilities(Numpy, Scipy)
  • 3. • Portable • Easy to understand • Flexible – no hard rules • More flexible in solving problems using different methods • Developer productivity • Support libraries • Software quality • Access to advanced mathematical, statistical and database functions
  • 4. Compiler • A compiler is a program that converts a program written in a programming language into a program in the native language, called machine language, of the machine that is to execute the program.
  • 5. From Algorithms to Hardware (with compiler) Algorithm Program A real computer Translate (by a human being) Translate (by compiler program)
  • 6. The Program Development Process (Data Flow) Editor Compiler A real computer Algorithm Program in programming language Program in machine’s language Input Output
  • 7. The Program Development Process (Control Flow) Edit Compile Run Syntax errors Input Output Runtime errors
  • 8. Interpreter • An alternative to a compiler is a program called an interpreter. Rather than convert our program to the language of the computer, the interpreter takes our program one statement at a time and executes a corresponding set of machine instructions.
  • 10. • Python versions – Python 2(released on16th october 2000) – Python 3(released on 3rd december 2008 with more testing and new features) • Derived from other languages – C,C++, Unix, Shell, Smalltalk, Algol-68 • Different python implementation – Jython – IronPython – Stackless Python – PyPy
  • 11. Applications of Python • System programming • Desktop applications • Database applications • Internet scripting • Component integration • Rapid prototyping • Web mapping • Computer vision for image and video processing • Gaming, XML, Robotics • Numeric and scientific programming
  • 12. 2 modes for using Python interpreter • Interactive mode – Without creating python script file and passing it to interpreter, directly execute code to python prompt • Eg. >>> print("hello world") hello world >>> x=[0,1,2,3.5,”hai”] >>> x >>> [0, 1, 2, 3.5, “hai”] >>> 2+3 >>> 5 >>> len(‘hello’) >>> 5 >>> ‘hello’ + ‘welcome’ >>> ‘hello welcome’
  • 13. Running Python in script mode • programmers can store Python script source code in a file with the .py extension, and use the interpreter to execute the contents of the file. • To execute the script by the interpreter, the name of the file is informed to the interpreter. • For example, if source script name MyFile.py, to run the script on Unix: python MyFile.py • Working with the interactive mode is better when Python programmers deal with small pieces of code as you can type and execute them immediately, but when the code is more than 2-4 lines, using the script for coding can help to modify and use the code in future
  • 14. Syntax and Semantics • Comments in python begin by # – Ignored by interpreter – Standalone comments/inline comments # ------ – Multiline comments /* ---------- ----- */ • End of line marker “” in multiline expression – Within parenthesis no need of “” • Code blocks are denoted by indentation – Indented code block preceded by : on previous line • Whitespaces within line does not matter • Parenthesis are for grouping or calling
  • 15. • Eg. • x=5,y=0 • if x<4: y=x*2 print(y) • if x<4: y=x*2 print(y)
  • 16. Frameworks • Anaconda – Anaconda is free and open source distribution of Python and R programming language for data science and machine learning related applications. It simplify package management and deployment using package management system conda • Jupyter – Jupyter Notebook is a open source web application that allow to create and share documents contain live code, equations, visualizations. Also used for data cleaning and transformation, numerical simulation, statistical modeling, data visualization, machine learning
  • 17. Comments • Often we want to put some documentation in our program. These are comments for explanation, but not executed by the computer. • If we have # anywhere on a line, everything following this on the line is a comment – ignored
  • 18. To run python interactively • IDLE (Python 3.7 – 32bit) • IDLE (Python 3.10 – 64bit) • Desktop GUI that edit, run, browse and debug python programs (all from single interface) • Features – 100% pure python – Cross platform(same on windows, unix, Mac os) – 2 windows • Python Shell window(interactive python interpreter) with colorizing of code, input, output, error message • Editor window(undo, colorizing, smart indent, auto completion & other features) – Debugging with breakpoints, stepping and viewing of global & local namespaces
  • 19. IDLE – Development Environment • IDLE helps you program in Python by: – color-coding your program code – debugging – auto-indent – interactive shell 19
  • 20. Example Python • Hello World print “hello world” • Prints hello world to standard out • Open IDLE and try it out • Follow along using IDLE 20
  • 21. • IDLE usability features: – Auto indent and un-indent for python code – Auto completion – Balloon helps popups the syntax for particular function call when type ( – Popup selection list of attributes and methods when type classname/modulename . – Either pause or press Tab
  • 22. • Other most commonly used IDEs for Python – Eclipse and PyDev – Komodo – NetBeans IDE for Python – PythonWin – Wing, VisualStudio, etc..
  • 23. Python Interpretation • Lexical analysis – Statements divided into group of tokens – 5 types of tokens • Delimiter(used for grouping, punctuation, assignment) eg.() [] {} , : ; “ ‘ • Literals(have fixed value) • Identifier • Operator • keywords • Syntax analysis – Syntax defines the format or structure of statements and sentences • Semantic analysis – Semantics defines the meaning of sentences and statements
  • 24. Data types in Python • Number – Integer, float, long integer, complex • String • Boolean • List • Set • Tuple • Dictionary
  • 25. Numeric Data Types • int This type is for whole numbers, positive or negative. Unlimited length – Examples: 23, -1756 >>> print(245673649874+2) >>> 245673649876 >>> print(0b10) or (0B10) # binary >>> 2 >>> print(0x20) # hex >>> 32 • float This type is for numbers with possible fraction parts. Examples: 23.0, -14.561
  • 26. >>> a = 1 #int >>> l = 1000000L # Long >>> e = 1.01325e5 # float >>> f = 3.14159 # float >>> c = 1+1 j # Complex >>> print(f ∗c / a ) (3.14159+3.14159 j ) >>> printf(c.real, c.imag) 1.0 1.0 >>> abs ( c ) 1.4142135623730951 del var1,var2,var3,... Delete the reference to the number object using del.
  • 27. • Complex numbers >>>2+3j 2+3j >>>(2+3j) * 5 10+15j >>>2+3j * 5 2+15j >>> (2+3j).real 2.0 >>> (2+3j).imag 3.0 >>> (2+3j).conjugate() (2-3j)
  • 28. • Boolean – True(1) / False(0) >>>bool(1) True >>>bool(0) False >>>bool(‘1’) True >>>bool(‘0’) True >>>bool(‘hello’) True >>>bool((1)) True >>>bool((0)) False >>>bool(()) False >>>bool([]) False
  • 30. >>> t = True >>> f = not t False >>> f or t True >>> f and t False
  • 31. Operators in Python • Arithmetic operators • Comparison operators(conditional) • Logical operators • Assignment operators • Bitwise operators • Membership operators • Identity operators
  • 32. Arithmetic Operators Arithmetic operators are used with numeric values to perform common mathematical operations The operations for integers are: + for addition - for subtraction * for multiplication / for integer division: The result of 14/5 is 2.8 // floor division 14 //5 = 2 % for remainder: The result of 14 % 5 is 4 ** exponentiation ** take more precedence than * / % // *, /, % take precedence over +, - Eg. x + y * z will execute y*z first Use parentheses to dictate order you want. Eg. (x+y) * z will execute x+y first.
  • 33. • When computing with floats, / will indicate regular division with fractional results. • Constants will have a decimal point. • 14.0/5.0 will give 2.8 • 14/5 gives 2.8
  • 34. Comparison Operators Comparison operators are used to compare two values Operator Name Example == Equal x == y != Not equal x != y > Greater than x > y < Less than x < y >= Greater than or equal to x >= y <= Less than or equal to x <= y
  • 35. Logical Operators Logical operators are used to combine conditional statements Operator Description and Returns True if both statements are true Eg. x < 5 and x < 10 or Returns True if one of the statements is true Eg. x < 5 or x < 4 not Reverse the result, returns False if the result is true Eg. not(x < 5 and x < 10)
  • 36. Bitwise Operators Bitwise operators are used to compare (binary) numbers Operator Name Description & AND Sets each bit to 1 if both bits are 1 | OR Sets each bit to 1 if one of two bits is 1 ^ XOR Sets each bit to 1 if only one of two bits is 1 ~ NOT Inverts all the bits << Zero fill left shift Shift left by pushing zeros in from the right and let the leftmost bits fall off >> Signed right shift Shift right by pushing copies of the leftmost bit in from the left, and let the rightmost bits fall off
  • 37. Bitwise Operators Bitwise operators are used to compare (binary) numbers Operator Name Description & AND Sets each bit to 1 if both bits are 1 | OR Sets each bit to 1 if one of two bits is 1 ^ XOR Sets each bit to 1 if only one of two bits is 1 ~ NOT Inverts all the bits << Zero fill left shift Shift left by pushing zeros in from the right and let the leftmost bits fall off >> Signed right shift Shift right by pushing copies of the leftmost bit in from the left, and let the rightmost bits fall off
  • 38. Assignment operators Assignment operators are used to assign values to variables Operator Example Same As = x = 5 x = 5 += x += 3 x = x + 3 -= x -= 3 x = x – 3 *= x *= 3 x = x * 3 /= x /= 3 x = x / 3 %= x %= 3 x = x % 3 //= x //= 3 x = x // 3 **= x **= 3 x = x ** 3 &= x &= 3 x = x & 3 |= x |= 3 x = x | 3 ^= x ^= 3 x = x ^ 3 >>= x >>= 3 x = x >> 3 <<= x <<= 3 x = x << 3
  • 39. Membership Operators Membership operators are used to test if a sequence is presented in an object Operator Description in Returns True if a sequence with the specified value is present in the object Eg. x in y not in Returns True if a sequence with the specified value is not present in the object Eg. x not in y
  • 40. Identity Operators Identity operators are used to compare the objects, not if they are equal, but if they are actually the same object, with the same memory location Operator Description is Returns True if both variables are the same object Eg. x is y is not Returns True if both variables are not the same object Eg. x is not y
  • 41. • Strings – continuous set of characters within ‘ ‘ or “ “ • ‘hai’ same as “hai” >>>print(“hello”) hello >>>print(“ “) ‘ ‘ >>>type(“hello”) <class ‘str’>
  • 42. >>> word = " h e l l o " >>> 2∗word + " wo rld “ h e l l o h e l l o wo rld >>> p ri n t (word [ 0 ] + word [ 2 ] + word[ −1]) h l o >>> word [ 0 ] = ’H ’ >>>print(word) Hello >>> x , y = 1 , 1.234 >>> print(x,y) 1 1.234
  • 43. • String special operators: + concatenation * repetition [ ] give character at index [ : ] range of characters in – membership (return true if char exist in string) not in - membership (return true if char not exist in string)
  • 44. str = 'Hello World!' print(str) print(str[0]) print(str[2:5]) print(str[2:]) print(str * 2) print(str + "TEST")
  • 45. • Output: Hello World! H llo llo World! Hello World!Hello World! Hello World!TEST
  • 46. str = 'HelloWorld' print(str) print(str[-1]) print(str[1:6]) print(str[2:-3]) print(str[ :-7]) print(str[-3: ]) print(str[: : -1]) Output HelloWorld d elloW lloWo Hel rld dlroWolleH
  • 47. String methods • capitalize() • title() • endswith(suffix,beg=0,end=len(string)) • find(string, beg=0,end=len(string)) • isalnum() • isdigit() • islower() • isspace() • istitle() • isupper()
  • 48. • join() • len() • lower() • upper() • lstrip() • max() • min() • replace() • rstrip() • split() • swapcase()
  • 49. String Methods • Assign a string to a variable • In this case “hw” • hw.title() • hw.upper() • hw.isdigit() • hw.islower() 49
  • 50. String Methods • The string held in your variable remains the same • The method returns an altered string • Changing the variable requires reassignment – hw = hw.upper() – hw now equals “HELLO WORLD” 50
  • 51. join() method is a string method and returns a string in which the elements of the sequence have been joined by the str separator Eg. list1 = ['1','2','3','4'] s = "-" s.join(list1) 1-2-3-4
  • 52. split() - split a string into a list where each word is a list item Eg. txt = "welcome to the jungle“ x = txt.split() print(x) ['welcome', 'to', 'the', 'jungle']
  • 53. >>> a = ’ h e l l o wo rld ’ >>> a . s t a r t s w i t h ( ’ h e l l ’ ) True >>> a . endswith ( ’ l d ’ ) True >>> a . upper ( ) ’HELLO WORLD’ >>> a . upper ( ) . lower ( ) ’ h e l l o wo rld ’ >>> a . s p l i t ( ) [ ’ h e l l o ’ , ’ wo rld ’ ] >>> ’ ’ . j o i n ( [ ’ a ’ , ’ b ’ , ’ c ’ ] ) ’ a b c ’ >>> x , y = 1 , 1.234 >>>”x=%s” %x x=1
  • 54. Runtime user Input • To get input from the user, we use an assignment statement of the form <variable> = input(<prompt>) it always treat the input value as string. • Here – <prompt> would be replaced by a prompt for the user inside quotation marks – If there is no prompt, the parentheses are still needed • Semantics – The prompt will be displayed – User enters number – Value entered is stored as the value of the variable
  • 55. • To get int or float input from the user, we use typecasting before input statement of the form <variable> = (int)input(<prompt>) it will treat the input value as int. <variable> = (float)input(<prompt>) it will treat the input value as float.
  • 56. Print Statement • For output we use statements of the form print <expression> • Semantics – Value of expression is computed – This value is displayed • Several expressions can be printed – separate them by commas • Eg. a,b=2,3.5 print(a+b, b*a) 5.5 7.0
  • 57. Example - Fahrenheit to Centigrade • We want to convert a Fahrenheit temperature to Centigrade. • The formula is C = (F -32) x 5/9 • We use type float for the temperatures.
  • 60. Tuples List: List items are enclosed within [ ] Lists can be updated Tuple: Tuple items are enclosed within ( ) Tuples can’t be updated Tuples can be thought of readonly list
  • 62. Set • Sets are used to store multiple items in a single variable. • Set items can not be updated, but items can be removed or added. • Sets are written with curly brackets. • Not allow duplicate items • Items can’t be referred by index or key • Eg. s1={1,1,1,2,2,2,3,3,4,5,5,5,5,5} print(s1) {1,2,3,4,5}
  • 63. Dictionary • Similar to associative arrays or hashes in perl • Key value pairs • Key=almost any data type(number or string) • Value=any arbitrary python object • Nested dictionaries – Define dictionary inside another dictionary – Eg. d={"id":101, "name":"AAA", "dept":"QA“, “addr”:{‘street’:’new colony 2nd cross street’, ‘town’:’porur’, ‘city’:’chennai’, ‘pincode’:600116} }
  • 64. Dic.py d={"id":101, "name":"AAA", "dept":"QA"} print(d) print("Emp ID=",d['id']) print("Emp Name=",d['name']) print("Emp Dept=",d['dept']) d['dept']="RA" print("Changed Emp Dept=",d['dept']) d['score']=95 print(d) d.pop('dept') print("After Pop:") print(d) print(d['dept'])
  • 65. output {'id': 101, 'name': 'AAA', 'dept': 'QA'} Emp ID= 101 Emp Name= AAA Emp Dept= QA Changed Emp Dept= RA {'id': 101, 'name': 'AAA', 'dept': 'RA', 'score': 95} After Pop: {'id': 101, 'name': 'AAA', 'score': 95} Traceback (most recent call last): File "C:/Users/Admin/AppData/Local/Programs/Python/Python37-32/dic.py", line 13, in <module> print(d['dept']) KeyError: 'dept'
  • 66. Conditional statements • 3 types of statements in python – Selection/conditional – Iteration – Jump • Selection/conditional statements – If – If else – If elif else
  • 67. • if <condn>: <then statements> • Eg. • if x<0: print(“x is negative”)
  • 68. • if <condn>: <then statements> else: <else statements> Eg: if x%2 ==0: print(“Even”) else: print(“Odd”)
  • 69. Nested if If elif else If <condn1>: <statements> elif <condn2>: <statements> elif <condn3>: <statements> else: <statements>
  • 71. Eg. m=85 if m>90 and m<=100 : print(“1st class”) elif m>80 and m<=90 : print(“2nd class”) elif m>70 and m<=80 : print(“3rd class”) elif m>60 and m<=70 : print(“4th class”) elif m>50 and m<=60 : print(“5th class”) else: print(“FAIL”)
  • 72. Iteration/Loop statements • for • while for: for <variable> in <sequence> : <body of loop> Eg. Printing 1 to 10 for i in range(1,11): print(i) Printing odd numbers from 1 to 100 for i in range(1,101): if(i%2 != 0): print(i)
  • 75. Eg. Sum of n natural numbers n = int(input("Enter n: ")) sum = 0, i = 1 while i <= n: sum = sum + i i = i+1 print("The sum is", sum) Output: Enter n: 10 The sum is 55
  • 76. Functions – builtin functions – User defined functions • Defining function: – Begin with def followed by function name and () – Input parameters / arguments within () and followed by : at end – Function body (code block) is intended – Return [expr]
  • 77. • eg: s=“John” def printstr(s): “Welcome to Python” print(s) return
  • 78. • Eg; def add(a,b): return a+b >>>r=add(5,6) print(r) 11
  • 79. Eg. Fibonancci series generation n=int(input(“enter limit”)) def fib(n): a,b=0,1 while a<n: print(a) a=b b=a+b print()
  • 80. Eg. Fibnonaaci series return a list of numbers from function def fib(n): r=[] a,b=0,1 while a<n: r.append(a) a=b b=a+b return r L=fib(10) print(L) 0 1 1 2 3 5 8
  • 81. • 4 types of arguments – Position arguments – Keyword arguments – Default arguments – Variable length arguments
  • 82. • Positional arguments Eg. def add(a,b): c=a+b print(c) add(5,6) Eg. def person(name, age): print(“Name=“, name) print(“Age=“, age) person(‘John’, 28)
  • 83. • Keyword arguments Eg. def person(name, age): print(“Name=“, name) print(“Age=“, age) person(age=28, name=‘John’)
  • 84. • Default arguments Eg. def person(name, age=18): print(“Name=“, name) print(“Age=“, age) person(‘John’) person(‘Karan’,25) Eg. def area(pi=3.14, r=2): res=pi*r*r print(res) area() area(r=5)
  • 85. Eg. def greeting(name, msg=“welcome”) print(“Hello”, name, msg) greeting(“John”) greeting(“John”, “Good morning”)
  • 86. • Variable length arguments – When we need to process function for more arguments than defined in function – variable length arguments used – * placed in front of all non keyword variable length arguments – This tuple remains empty when no additional arguments specified during function call
  • 87. Eg. def sum(a,*b): print(a) print(b) c=a for i in b: c=c+i print(c) sum(5,6) sum(5,6,14,25,37)
  • 88. Eg. def sum(*b): print(b) c=0 for i in b: c=c+i print(c) Sum(5) sum(5,6) sum(5,6,14,25,37)
  • 89. Keyworded variable length arguments Eg. def person(name, **data): print(name) for i , j in data.items() : print(i,j) person(‘Navin’, age=28, city=‘Mumbai’, mobile=9840374322) o/p: Navin age 28 city Mumbai mobile 9840374322
  • 90. Pass by value Eg. def update(x): x=8 print(“x=“, x) a=10 update(a) print(“a=“,a) o/p: x=8 a=10
  • 91. • In python no pass by value or pass by reference • In python everything are objects • id() returns object id or memory reference(memory location id)
  • 95. break Jump out of the closest loop Eg. max=10 x=int(input(“enter a number”)) i=1 while i<=x: if i>max: print(“crossed max limit”) break print(“Hello”) i=i+1 print(“Bye”)
  • 96. continue Used to skip an iteration of the loop when a condition is met Eg. for i in range(1, 101): if i%3 == 0 : continue print(i) print(“Bye”) O/p: 1,2,4,5,7,8,10,11,13,14,16,17,……….
  • 97. For i in range(1, 101): if(i%3 == 0 or i%5 == 0): continue print(i) print(“Bye”) O/p: 1,2,4,7,8,11,13,14,16,17,……………….
  • 98. pass No-operation, placeholder used when syntax requires statement but we don’t have nothing useful to execute. Eg. i=1 while i<=10 : if i==6 : print(“skip : simply pass”) pass else: print(i) i=i+1
  • 100. Loop else • else block associated with loop Eg. l=[11,33,52,39,66,75,37,21,24,44,13] for i in l: if i%2 == 0 : print(“Divisible by 5: “, i) break else: print(“Not found”)
  • 101. Global variables Eg. a=10 def func(): a=15 print(“inside function “, a) func() print(“outside function”, a) o/p: inside function 15 outside function 10
  • 102. Eg. a=10 def func(): global a a=15 print(“inside function “, a) func() print(“outside function”, a) o/p: inside function 15 outside function 15
  • 103. Eg. a=10 print(id(a)) def func(): a=15 x=globals()[‘a’] print(id(x)) print(“inside function “, a) globals()[‘a’]=20 func() print(“outside function”, a) o/p: 265959824 265959824 inside function 15 outside function 20
  • 104. Lambda expressions • Functions without name – anonymous function • lambda function or lambda expressions is a small anonymous function • Can take any no. of arguments but only one expression allowed • Functions are objects in python Syntax: lambda arguments : expr Eg. x=lambda a: a+10 print(x(5)) O/p: 15
  • 105. • multiply argument a with b and return result Eg. x=lambda a,b : a*b print(x(5,6)) o/p: 30 Eg. f=lambda a : a*a result=f(5) print(result)
  • 106. • The power of lambda is better when we use them as an anonymous function inside another function Eg. def func(n): return lambda a : a*n r=func(2) print(r(11)) o/p: 22
  • 107. Eg. def func(n): return lambda a : a*n r1=func(2) r2=func(3) print(r1(11)) print(r2(11)) o/p: 22 33
  • 108. filter Eg. def is_even(n): return n%2 == 0 num=[11,33,52,39,66,75,37,21,24,44,13] even=list(filter(is_even, num)) print(even)
  • 110. map Eg. def update(n): return 2*n num=[11,33,52,39,66,75,37,21,24,44,13] even=list(filter(lambda n: n%2==0, num)) double=list(map(update, even)) print(double)
  • 111. Eg. num=[11,33,52,39,66,75,37,21,24,44,13] even=list(filter(lambda n: n%2==0, num)) double=list(map(lambda n : 2*n, even)) print(double)
  • 112. reduce Eg. from functools import reduce def add_all(a,b): return a+b num=[11,33,52,39,66,75,37,21,24,44,13] even=list(filter(lambda n: n%2==0, num)) double=list(map(lambda n : 2*n, even)) print(double) sum=reduce(add_all, double) print(sum)
  • 113. Eg. from functools import reduce num=[11,33,52,39,66,75,37,21,24,44,13] even=list(filter(lambda n: n%2==0, num)) double=list(map(lambda n : 2*n, even)) print(double) sum=reduce(lambda a,b : a+b, double) print(sum)
  • 114. • Use lambda function when anonymous function is required for a short period of time • Lambda function does not need a name during function definition • Lambda functions can be used along with built-in functions such as map(), filter() and reduce()
  • 115. • Guidelines to use lambda function/expr: – If function can’t able to be expressed in one line, don’t use lambda – If function call uses several lambda expressions, difficult to understand code(not recommended) – If same function is used in many places, better to use normal function rather than lambda