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
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.
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)
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} }
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]
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
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
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”)
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
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