SlideShare a Scribd company logo
1 of 103
A Quick Tour of Python
Akansha Mittal
(2K21/AFI/12)
Write/Edit
Run
with some input
OK?
YES
More
Inputs?
YES
NO
NO
Filename, preferred extension is py
User Program
Interacting with Python Programs
ā€¢ Python program communicates its results to
user using print
ā€¢ Most useful programs require information
from users
ā€“ Name and age for a travel reservation system
ā€¢ Python 3 uses input to read user input
input
ā€¢ Take as argument a string to print as a prompt
ā€¢ Returns the user typed value as a string
IN[1]:
IN[2]:
IN[3]:
( )
Types in Python
ā€¢ int
ā€“ Bounded integers, e.g. 732 or -5
ā€¢ float
ā€“ Real numbers, e.g. 3.14 or 2.0
ā€¢ long
ā€“ Long integers
ā€¢ str
ā€“ Strings, e.g. ā€˜helloā€™ or ā€˜Cā€™
Example of Types
Type Conversion (Type Cast)
ā€¢ Conversion of value of one type to other
ā€¢ We are used to int ā†” float conversion in Math
ā€“ Integer 3 is treated as float 3.0 when a real
number is expected
ā€“ Float 3.6 is truncated as 3, or rounded off as 4 for
integer contexts
ā€¢ Type names are used as type converter
functions
Type Conversion Examples
Note that float to int conversion
is truncation, not rounding off
Type Conversion and Input
Operators
ā€¢ Arithmetic
ā€¢ Comparison
ā€¢ Assignment
ā€¢ Logical
ā€¢ Bitwise
ā€¢ Membership
ā€¢ Identity
+ - * // / % **
== != > < >= <=
= += -= *= //= /= %= **=
and or not
in not in
is is not
& | ^ ~ >> <<
Variables
ā€¢ A name associated with an
object
ā€¢ Assignment used for binding
m = 64;
c = ā€˜Acadsā€™;
f = 3.1416;
ā€¢ Variables can change their
bindings
f = 2.7183;
64
Acads
3.1416
2.7183
m
c
f
Assignment Statement
ā€¢ A simple assignment statement
Variable = Expression;
ā€¢ Computes the value (object) of the expression
on the right hand side expression (RHS)
ā€¢ Associates the name (variable) on the left
hand side (LHS) with the RHS value
ā€¢ = is known as the assignment operator.
Multiple Assignments
ā€¢ Python allows multiple assignments
x, y = 10, 20
ā€¢ Evaluation of multiple assignment statement:
ā€“ All the expressions on the RHS of the = are first
evaluated before any binding happens.
ā€“ Values of the expressions are bound to the
corresponding variable on the LHS.
x, y = 10, 20
x, y = y+1, x+1
Binds x to 10 and y to 20
x is bound to 21
and y to 11 at the
end of the program
Programming using Python
Operators and Expressions
Binary Operations
Op Meaning Example Remarks
+ Addition 9+2 is 11
9.1+2.0 is 11.1
- Subtraction 9-2 is 7
9.1-2.0 is 7.1
* Multiplication 9*2 is 18
9.1*2.0 is 18.2
/ Division 9/2 is 4.25 In Python3
9.1/2.0 is 4.55 Real div.
// Integer Division 9//2 is 4
% Remainder 9%2 is 1
The // operator
ā€¢ Also referred to as ā€œinteger divisionā€
ā€¢ Result is a whole integer (floor of real
division)
ā€“ But the type need not be int
ā€“ the integral part of the real division
ā€“ rounded towards minus infinity (āˆ’āˆž)
ā€¢ Examples
9//4 is 2 (-1)//2 is -1 (-1)//(-2) is 0
1//2 is 0 1//(-2) is -1 9//4.5 is 2.0
The % operator
ā€¢ The remainder operator % returns the
remainder of the result of dividing its
first operand by its second.
9%4 is 1 (-1)%2 is 1 (-1)//(-2) is 0
9%4.5 is 0.0 1%(-2) is 1 1%0.6 is 0.4
Ideally: x == (x//y)*y + x %y
Conditional Statements
ā€¢ In daily routine
ā€“If it is very hot, I will skip
exercise.
ā€“If there is a quiz tomorrow, I will
first study and then sleep.
Otherwise I will sleep now.
ā€“If I have to buy coffee, I will
go left. Else I will go
straight.
if-else statement
ā€¢ Compare two integers and print the min.
1. Check if x is less
than y.
2. If so, print x
3. Otherwise, print y.
if x < y:
print (x)
else:
print (y)
print (ā€˜is the minimumā€™)
x,y = 6,10
if x < y:
print (x)
else:
print (y)
print (ā€˜is the minā€™)
x y
6 10
Run the program
Output
6
Indentation
ā€¢ Indentation is important in Python
ā€“ grouping of statement (block of statements)
ā€“ no explicit brackets, e.g. { }, to group statements
if statement (no else!)
ā€¢ General form of the if statement
ā€¢ Execution of if statement
ā€“ First the expression is evaluated.
ā€“ If it evaluates to a true value, then S1 is
executed and then control moves to the S2.
ā€“ If expression evaluates to false, then control
moves to the S2 directly.
if boolean-expr :
S1
S2
S1
S2
if-else statement
ā€¢ General form of the if-else statement
ā€¢ Execution of if-else statement
ā€“ First the expression is evaluated.
ā€“ If it evaluates to a true value, then S1 is executed and
then control moves to S3.
ā€“ If expression evaluates to false, then S2 is executed
and then control moves to S3.
ā€“ S1/S2 can be blocks of statements!
if boolean-expr :
S1
else:
S2
S3
S2
S1
S3
Nested if, if-else
if a <= b:
if a <= c:
ā€¦
else:
ā€¦
else:
if b <= c) :
ā€¦
else:
ā€¦
Elif
ā€¢ A special kind of nesting is the chain of if-
else-if-else-ā€¦ statements
ā€¢ Can be written elegantly using if-elif-..-else
if cond1:
s1
elif cond2:
s2
elif cond3:
s3
elif ā€¦
else
last-block-of-stmt
if cond1:
s1
else:
if cond2:
s2
else:
if cond3:
s3
else:
ā€¦
Summary of if, if-else
ā€¢ if-else, nested if's, elif.
ā€¢ Multiple ways to solve a problem
ā€“issues of readability,
maintainability
ā€“and efficiency
Quiz
ā€¢ What is the value of expression:
a) Run time crash/error
b) I donā€™t know / I donā€™t care
c) False
d) True
(5<2) and (3/0 > 1)
The correct answer is
False
Short-circuit Evaluation
ā€¢ Do not evaluate the second operand of binary
short-circuit logical operator if the result can be
deduced from the first operand
ā€“ Also applies to nested logical operators
not( (2>5) and (3/0 > 1) ) or (4/0 < 2)
Evaluates to true
false false
true true
3 Factors for Expr Evaluation
ā€¢ Precedence
ā€“ Applied to two different class of operators
ā€“ + and *, - and *, and and or, ā€¦
ā€¢ Associativity
ā€“ Applied to operators of same class
ā€“ * and *, + and -, * and /, ā€¦
ā€¢ Order
ā€“ Precedence and associativity identify the operands for
each operator
ā€“ Not which operand is evaluated first
ā€“ Python evaluates expressions from left to right
ā€“ While evaluating an assignment, the right-hand side is
evaluated before the left-hand side.
ā€¢ Representation of real numbers in a computer
can not be exact
ā€“ Computers have limited memory to store data
ā€“ Between any two distinct real numbers, there are
infinitely many real numbers.
ā€¢ On a typical machine running Python, there are
53 bits of precision available for a Python float
Caution about Using Floats
ā€¢ Because of the approximations, comparison of
floats is not exact.
ā€¢ Solution?
ā€¢ Instead of
x == y
use
abs(x-y) <= epsilon
where epsilon is a suitably chosen small value
Comparing Floats
Programming using Python
Loops
Printing Multiplication Table
5 X 1 = 5
5 X 2 = 10
5 X 3 = 15
5 X 4 = 20
5 X 5 = 25
5 X 6 = 30
5 X 7 = 35
5 X 8 = 40
5 X 9 = 45
5 X 10 = 50
Programā€¦
n = int(input('Enter a number: '))
print (n, 'X', 1, '=', n*1)
print (n, 'X', 2, '=', n*2)
print (n, 'X', 3, '=', n*3)
print (n, 'X', 4, '=', n*4)
print (n, 'X', 5, '=', n*5)
print (n, 'X', 6, '=', n*6)
ā€¦.
Too much
repetition!
Can I avoid
it?
Print n X i = n*i
i = i+1
Input n
i = 1
i <=10
TRUE FALSE
Printing Multiplication Table
Stop
Loop
Loop Entry
Loop Exit
Printing Multiplication Table
n = int(input('n=? '))
i = 1
while (i <= 10) :
print (n ,'X', i, '=', n*i)
i = i + 1
print ('doneā€˜)
Print n x i = ni
i = i+1
Input n
i = 1
TRUE
i <=10
FALSE
Stop
While Statement
1. Evaluate expression
2. If TRUE then
a) execute statement1
b) goto step 1.
3. If FALSE then execute statement2.
while (expression):
S1
S2
FALSE
TRUE
S1
expression
S2
For Loop
ā€¢ Print the sum of the reciprocals of the
first 100 natural numbers.
rsum=0.0# the reciprocal sum
# the for loop
for i in range(1,101):
rsum = rsum + 1.0/i
print ('sum is', rsum)
For loop in Python
ā€¢ General form
for variable in sequence:
stmt
range
ā€¢ range(s, e, d)
ā€“generates the list:
[s, s+d, s+2*d, ā€¦, s+k*d]
where s+k*d < e <= s+(k+1)*d
ā€¢ range(s, e) is equivalent to range(s, e, 1)
ā€¢ range(e) is equivalent to range(0, e)
Exercise: What if d is negative? Use python
interpreter to find out.
# print all odd numbers < 10
i = 1
while i <= 10:
if i%2==0: # even
continue
print (i, end=ā€˜ ā€˜)
i = i+1
Quiz
ā€¢ What will be the output of the following
program
# print all odd numbers < 10
i = 1
while i <= 10:
if i%2==0: # even
continue
print (i, end=ā€˜ ā€˜)
i = i+1
Continue and Update Expr
ā€¢ Make sure continue does not bypass update-
expression for while loops
i is not incremented
when even number
encountered.
Infinite loop!!
Programming using Python
f(unctions)
Parts of a function
Input
Output
f
x = max(6, 4)
def max (a, b):
ā€˜ā€™ā€™return maximum among a and bā€™ā€™ā€™
if (a > b):
return a
else:
return b
keyword
Function Name
2 arguments
a and b
(formal args)
Body of thefunction,
indented w.r.t the
def keyword
Documentation comment
Call to the function.
Actual args are 6 and 4.
Keyword Arguments
def printName(first, last, initials) :
if initials:
print (first[0] + '. ' + last[0] + '.')
else:
print (first, last)
Call Output
printName('Acads', 'Institute', False) Acads Institute
printName('Acads', 'Institute', True) A. I.
printName(last='Institute', initials=False, first='Acads') Acads Institute
printName('Acads', initials=True, last='Institute') A. I.
Note use of [0]
to get the first
character of a
string. More on
this later.
Keyword Arguments
ā€¢ Parameter passing where formal is bound to
actual using formal's name
ā€¢ Can mix keyword and non-keyword arguments
ā€“ All non-keyword arguments precede keyword
arguments in the call
ā€“ Non-keyword arguments are matched by position
(order is important)
ā€“ Order of keyword arguments is not important
Default Values
def printName(first, last, initials=False) :
if initials:
print (first[0] + '. ' + last[0] + '.')
else:
print (first, last)
Call Output
printName('Acads', 'Institute') Acads Institute
printName(first='Acads', last='Institute', initials=True) A. I.
printName(last='Institute', first='Acads') Acads Institute
printName('Acads', last='Institute') Acads Institute
Note the use
of ā€œdefaultā€
value
Default Values
ā€¢ Allows user to call a function with fewer
arguments
ā€¢ Useful when some argument has a fixed value
for most of the calls
ā€¢ All arguments with default values must be at
the end of argument list
ā€“ non-default argument can not follow default
argument
Globals
ā€¢ Globals allow functions to communicate with
each other indirectly
ā€“ Without parameter passing/return value
ā€¢ Convenient when two seemingly ā€œfar-apartā€
functions want to share data
ā€“ No direct caller/callee relation
ā€¢ If a function has to update a global, it must re-
declare the global variable with global
keyword.
Globals
PI = 3.14
def perimeter(r):
return 2 * PI * r
def area(r):
return PI * r * r
def update_pi():
global PI
PI = 3.14159
defines PI to be of float type with value
3.14. PI can be used across functions. Any
change to PI in update_pi will be visible to
all due to the use of global.
>>> print(area (100))
31400.0
>>> print(perimeter(10))
62.800000000000004
>>> update_pi()
>>> print(area(100))
31415.999999999996
>>> print(perimeter(10))
62.832
Programming with Python
T U E
P L S
L I S
S T
S T N
R I G S
Strings
ā€¢ Strings in Python have type str
ā€¢ They represent sequence of characters
ā€“ Python does not have a type corresponding to
character.
ā€¢ Strings are enclosed in single quotes(') or
double quotes(ā€œ)
ā€“ Both are equivalent
ā€¢ Backslash () is used to escape quotes and
special characters
Strings
ā€¢ More readable when print is used
Length of a String
ā€¢ len function gives the length of a string
n is a single character:
the special character
representing newline
Concatenate and Repeat
ā€¢ In Python, + and * operations have special
meaning when operating on strings
ā€¢ + is used for concatenation of (two) strings
ā€¢ * is used to repeat a string, an int number of
time
ā€¢ Function/Operator Overloading
Concatenate and Repeat
Indexing
ā€¢ Strings can be indexed
ā€¢ First character has index 0
Indexing
ā€¢ Negative indices start counting from the right
ā€¢ Negatives indices start from -1
ā€¢ -1 means last, -2 second last, ...
Indexing
ā€¢ Using an index that is too large or too small
results in ā€œindex out of rangeā€ error
Slicing
ā€¢ To obtain a substring
ā€¢ s[start:end] means substring of s starting at
index start and ending at index end-1
ā€¢ s[0:len(s)] is same as s
ā€¢ Both start and end are optional
ā€“ If start is omitted, it defaults to 0
ā€“ If end is omitted, it defaults to the length of string
ā€¢ s[:] is same as s[0:len(s)], that is same as s
Slicing
More Slicing
A c a d s
0 1 2 3 4
-5 -4 -3 -2 -1
Understanding Indices for slicing
5
Out of Range Slicing
ā€¢ Out of range indices are ignored for slicing
ā€¢ when start and end have the same sign, if start
>=end, empty slice is returned
Why?
A c a d s
0 1 2 3 4
-5 -4 -3 -2 -1
Tuples
ā€¢ A tuple consists of a number of values
separated by commas
ā€¢ Empty and Singleton Tuples
Nested Tuples
ā€¢ Tuples can be nested
ā€¢ Note that course tuple is copied into student.
ā€“ Changing course does not affect student
Length of a Tuple
ā€¢ len function gives the length of a tuple
More Operations on Tuples
ā€¢ Tuples can be concatenated, repeated,
indexed and sliced
Unpacking Sequences
ā€¢ Strings and Tuples are examples of sequences
ā€“ Indexing, slicing, concatenation, repetition
operations applicable on sequences
ā€¢ Sequence Unpacking operation can be applied
to sequences to get the components
ā€“ Multiple assignment statement
ā€“ LHS and RHS must have equal length
Unpacking Sequences
( )
Lists
ā€¢ Ordered sequence of values
ā€¢ Written as a sequence of comma-separated
values between square brackets
ā€¢ Values can be of different types
ā€“ usually the items all have the same type
Lists
ā€¢ List is also a sequence type
ā€“ Sequence operations are applicable
Lists
ā€¢ List is also a sequence type
ā€“ Sequence operations are applicable
Repetition
( )
More Operations on Lists
ā€¢ L.append(x)
ā€¢ L.extend(seq)
ā€¢ L.insert(i, x)
ā€¢ L.remove(x)
ā€¢ L.pop(i)
ā€¢ L.pop()
ā€¢ L.index(x)
ā€¢ L.count(x)
ā€¢ L.sort()
ā€¢ L.reverse()
x is any value, seq is a sequence value (list, string, tuple, ā€¦),
i is an integer value
Mutable and Immutable Types
ā€¢ Tuples and List types look very similar
ā€¢ However, there is one major difference: Lists
are mutable
ā€“ Contents of a list can be modified
ā€¢ Tuples and Strings are immutable
ā€“ Contents can not be modified
Summary of Sequences
Operation Meaning
seq[i] i-th element of the sequence
len(seq) Length of the sequence
seq1 + seq2 Concatenate the two sequences
num*seq
seq*num
Repeat seq num times
seq[start:end] slice starting from start, and ending at end-1
e in seq True if e is present is seq, False otherwise
e not in seq True if e is not present is seq, False otherwise
for e in seq Iterate over all elements in seq (e is bound to one element per
iteration)
Sequence types include String, Tuple and List.
Lists are mutable, Tuple and Strings immutable.
Programming with Python
Sets and Dictionaries
Sets
ā€¢ An unordered collection with no duplicate
elements
ā€¢ Supports
ā€“ membership testing
ā€“ eliminating duplicate entries
ā€“ Set operations: union, intersection, difference,
and symmetric difference.
Sets
Create a set from
a sequence
{ }
Set Operations
{ }
{ }
{ }
{ }
{ }
Dictionaries
ā€¢ Unordered set of key:value pairs,
ā€¢ Keys have to be unique and immutable
ā€¢ Key:value pairs enclosed inside curly braces
{...}
ā€¢ Empty dictionary is created by writing {}
ā€¢ Dictionaries are mutable
ā€“add new key:value pairs,
ā€“change the pairing
ā€“delete a key (and associated value)
Operations on Dictionaries
Operation Meaning
len(d) Number of key:value pairs in d
d.keys() List containing the keys in d
d.values() List containing the values in d
k in d True if key k is in d
d[k] Value associated with key k in d
d.get(k, v) If k is present in d, then d[k] else v
d[k] = v Map the value v to key k in d
(replace d[k] if present)
del d[k] Remove key k (and associated value) from d
for k in d Iterate over the keys in d
Operations on Dictionaries
Operations on Dictionaries
Operations on Dictionaries
# Remember: for ... in iterates over keys only
# Sort values in a list
Dictionary Construction
ā€¢ The dict constructor: builds dictionaries
directly from sequences of key-value pairs
Programming with Python
File I/O
File I/O
ā€¢ Files are persistent storage
ā€¢ Allow data to be stored beyond program
lifetime
ā€¢ The basic operations on files are
ā€“ open, close, read, write
ā€¢ Python treat files as sequence of lines
ā€“ sequence operations work for the data read from
files
File I/O: open and close
open(filename, mode)
ā€¢ While opening a file, you need to supply
ā€“ The name of the file, including the path
ā€“ The mode in which you want to open a file
ā€“ Common modes are r (read), w (write), a (append)
ā€¢ Mode is optional, defaults to r
ā€¢ open(..) returns a file object
ā€¢ close() on the file object closes the file
ā€“ finishes any buffered operations
File I/O: Example
ā€¢ Do some writing
ā€¢ How to do it?
ā€¢ see the next few slides
File I/O: read, write and append
ā€¢ Reading from an open file returns the
contents of the file
ā€“ as sequence of lines in the program
ā€¢ Writing to a file
ā€“ IMPORTANT: If opened with mode 'w', clears the
existing contents of the file
ā€“ Use append mode ('a') to preserve the contents
ā€“ Writing happens at the end
File I/O: Examples
File I/O: Examples
(
( )
)
File I/O: Examples
Note empty line due to 'n'
( )
File I/O: Examples
Note the use of for ... in
for sequence
]
( )
File I/O: Examples
( )
( )
( )
Programming with Python
OOPS
OOP Terminology
ā€¢ Class
ā€¢ Class variable
ā€¢ Data member
ā€¢ Function overloading
ā€¢ Instance variable
ā€¢ Inheritance
ā€¢ Instance
ā€¢ Instantiation
ā€¢ Method
ā€¢ Object
ā€¢ Operator overloading
Class
class Employee:
'Common base class for all employees'
empCount = 0
def __init__(self, name, salary):
self.name = name
self.salary = salary
Employee.empCount += 1
def displayCount(self):
print "Total Employee %d" % Employee.empCount
def displayEmployee(self):
print "Name : ", self.name, ", Salary: ", self.salary
"This would create first object of Employee class"
emp1 = Employee("Zara", 2000)
"This would create second object of Employee class"
emp2 = Employee("Manni", 5000)
emp1.displayEmployee()
emp2.displayEmployee()
print "Total Employee %d" % Employee.empCount
Class Inheritance
class Parent: # define parent class
parentAttr = 100
def __init__(self):
print "Calling parent constructor"
def parentMethod(self):
print 'Calling parent method'
def setAttr(self, attr):
Parent.parentAttr = attr
def getAttr(self):
print "Parent attribute :", Parent.parentAttr
class Child(Parent): # define child class
def __init__(self):
print "Calling child constructor"
def childMethod(self):
print 'Calling child method'
c = Child() # instance of child
c.childMethod() # child calls its method
c.parentMethod() # calls parent's method
c.setAttr(200) # again call parent's method
c.getAttr() # again call parent's method
Overriding Methods
class Parent: # define parent class
def myMethod(self):
print 'Calling parent method'
class Child(Parent): # define child class
def myMethod(self):
print 'Calling child method'
c = Child() # instance of child
c.myMethod() # child calls overridden method
Overloading Operators
class Vector:
def __init__(self, a, b):
self.a = a
self.b = b
def __str__(self):
return 'Vector (%d, %d)' % (self.a, self.b)
def __add__(self,other):
return Vector(self.a + other.a, self.b + other.b)
v1 = Vector(2,10)
v2 = Vector(5,-2)
print v1 + v2
Data Hiding
An object's attributes may or may not be visible outside
the class definition. You need to name attributes with a
double underscore prefix, and those attributes then are
not be directly visible to outsiders.

More Related Content

Similar to Python.pptx

python notes.pdf
python notes.pdfpython notes.pdf
python notes.pdfRohitSindhu10
Ā 
Python4HPC.pptx
Python4HPC.pptxPython4HPC.pptx
Python4HPC.pptxpriyam737974
Ā 
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 basics
Python basicsPython basics
Python basicsHoang Nguyen
Ā 
Python basics
Python basicsPython basics
Python basicsTony Nguyen
Ā 
Python basics
Python basicsPython basics
Python basicsYoung Alista
Ā 
Python basics
Python basicsPython basics
Python basicsHarry Potter
Ā 
Python basics
Python basicsPython basics
Python basicsFraboni Ec
Ā 
Python basics
Python basicsPython basics
Python basicsJames Wong
Ā 
Introduction To Python.pptx
Introduction To Python.pptxIntroduction To Python.pptx
Introduction To Python.pptxAnum Zehra
Ā 
Python for Scientific Computing
Python for Scientific ComputingPython for Scientific Computing
Python for Scientific ComputingAlbert DeFusco
Ā 
Bikalpa_Thapa_Python_Programming_(Basics).pptx
Bikalpa_Thapa_Python_Programming_(Basics).pptxBikalpa_Thapa_Python_Programming_(Basics).pptx
Bikalpa_Thapa_Python_Programming_(Basics).pptxBikalpa Thapa
Ā 
Welcome to python workshop
Welcome to python workshopWelcome to python workshop
Welcome to python workshopMukul Kirti Verma
Ā 
Unit - 2 CAP.pptx
Unit - 2 CAP.pptxUnit - 2 CAP.pptx
Unit - 2 CAP.pptxmalekaanjum1
Ā 
ISTA 130 Lab 21 Turtle ReviewHere are all of the turt.docx
ISTA 130 Lab 21 Turtle ReviewHere are all of the turt.docxISTA 130 Lab 21 Turtle ReviewHere are all of the turt.docx
ISTA 130 Lab 21 Turtle ReviewHere are all of the turt.docxpriestmanmable
Ā 

Similar to Python.pptx (20)

pythonQuick.pdf
pythonQuick.pdfpythonQuick.pdf
pythonQuick.pdf
Ā 
python notes.pdf
python notes.pdfpython notes.pdf
python notes.pdf
Ā 
python 34šŸ’­.pdf
python 34šŸ’­.pdfpython 34šŸ’­.pdf
python 34šŸ’­.pdf
Ā 
Python4HPC.pptx
Python4HPC.pptxPython4HPC.pptx
Python4HPC.pptx
Ā 
lecture 2.pptx
lecture 2.pptxlecture 2.pptx
lecture 2.pptx
Ā 
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...
Ā 
Python basics
Python basicsPython basics
Python basics
Ā 
Python basics
Python basicsPython basics
Python basics
Ā 
Python basics
Python basicsPython basics
Python basics
Ā 
Python basics
Python basicsPython basics
Python basics
Ā 
Python basics
Python basicsPython basics
Python basics
Ā 
Python basics
Python basicsPython basics
Python basics
Ā 
Python basics
Python basicsPython basics
Python basics
Ā 
Introduction To Python.pptx
Introduction To Python.pptxIntroduction To Python.pptx
Introduction To Python.pptx
Ā 
Python for Scientific Computing
Python for Scientific ComputingPython for Scientific Computing
Python for Scientific Computing
Ā 
Bikalpa_Thapa_Python_Programming_(Basics).pptx
Bikalpa_Thapa_Python_Programming_(Basics).pptxBikalpa_Thapa_Python_Programming_(Basics).pptx
Bikalpa_Thapa_Python_Programming_(Basics).pptx
Ā 
Welcome to python workshop
Welcome to python workshopWelcome to python workshop
Welcome to python workshop
Ā 
Python.pdf
Python.pdfPython.pdf
Python.pdf
Ā 
Unit - 2 CAP.pptx
Unit - 2 CAP.pptxUnit - 2 CAP.pptx
Unit - 2 CAP.pptx
Ā 
ISTA 130 Lab 21 Turtle ReviewHere are all of the turt.docx
ISTA 130 Lab 21 Turtle ReviewHere are all of the turt.docxISTA 130 Lab 21 Turtle ReviewHere are all of the turt.docx
ISTA 130 Lab 21 Turtle ReviewHere are all of the turt.docx
Ā 

Recently uploaded

chaitra-1.pptx fake news detection using machine learning
chaitra-1.pptx  fake news detection using machine learningchaitra-1.pptx  fake news detection using machine learning
chaitra-1.pptx fake news detection using machine learningmisbanausheenparvam
Ā 
Call Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur Escorts
Call Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur EscortsCall Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur Escorts
Call Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur EscortsCall Girls in Nagpur High Profile
Ā 
Introduction to IEEE STANDARDS and its different types.pptx
Introduction to IEEE STANDARDS and its different types.pptxIntroduction to IEEE STANDARDS and its different types.pptx
Introduction to IEEE STANDARDS and its different types.pptxupamatechverse
Ā 
Coefficient of Thermal Expansion and their Importance.pptx
Coefficient of Thermal Expansion and their Importance.pptxCoefficient of Thermal Expansion and their Importance.pptx
Coefficient of Thermal Expansion and their Importance.pptxAsutosh Ranjan
Ā 
Extrusion Processes and Their Limitations
Extrusion Processes and Their LimitationsExtrusion Processes and Their Limitations
Extrusion Processes and Their Limitations120cr0395
Ā 
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...ranjana rawat
Ā 
What are the advantages and disadvantages of membrane structures.pptx
What are the advantages and disadvantages of membrane structures.pptxWhat are the advantages and disadvantages of membrane structures.pptx
What are the advantages and disadvantages of membrane structures.pptxwendy cai
Ā 
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur EscortsHigh Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur EscortsCall Girls in Nagpur High Profile
Ā 
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...Christo Ananth
Ā 
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptxDecoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptxJoĆ£o Esperancinha
Ā 
MANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLS
MANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLSMANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLS
MANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLSSIVASHANKAR N
Ā 
(RIA) Call Girls Bhosari ( 7001035870 ) HI-Fi Pune Escorts Service
(RIA) Call Girls Bhosari ( 7001035870 ) HI-Fi Pune Escorts Service(RIA) Call Girls Bhosari ( 7001035870 ) HI-Fi Pune Escorts Service
(RIA) Call Girls Bhosari ( 7001035870 ) HI-Fi Pune Escorts Serviceranjana rawat
Ā 
SPICE PARK APR2024 ( 6,793 SPICE Models )
SPICE PARK APR2024 ( 6,793 SPICE Models )SPICE PARK APR2024 ( 6,793 SPICE Models )
SPICE PARK APR2024 ( 6,793 SPICE Models )Tsuyoshi Horigome
Ā 
the ladakh protest in leh ladakh 2024 sonam wangchuk.pptx
the ladakh protest in leh ladakh 2024 sonam wangchuk.pptxthe ladakh protest in leh ladakh 2024 sonam wangchuk.pptx
the ladakh protest in leh ladakh 2024 sonam wangchuk.pptxhumanexperienceaaa
Ā 
HARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICS
HARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICSHARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICS
HARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICSRajkumarAkumalla
Ā 
Call Girls Delhi {Jodhpur} 9711199012 high profile service
Call Girls Delhi {Jodhpur} 9711199012 high profile serviceCall Girls Delhi {Jodhpur} 9711199012 high profile service
Call Girls Delhi {Jodhpur} 9711199012 high profile servicerehmti665
Ā 
Architect Hassan Khalil Portfolio for 2024
Architect Hassan Khalil Portfolio for 2024Architect Hassan Khalil Portfolio for 2024
Architect Hassan Khalil Portfolio for 2024hassan khalil
Ā 
College Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
College Call Girls Nashik Nehal 7001305949 Independent Escort Service NashikCollege Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
College Call Girls Nashik Nehal 7001305949 Independent Escort Service NashikCall Girls in Nagpur High Profile
Ā 
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130Suhani Kapoor
Ā 

Recently uploaded (20)

chaitra-1.pptx fake news detection using machine learning
chaitra-1.pptx  fake news detection using machine learningchaitra-1.pptx  fake news detection using machine learning
chaitra-1.pptx fake news detection using machine learning
Ā 
Call Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur Escorts
Call Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur EscortsCall Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur Escorts
Call Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur Escorts
Ā 
Introduction to IEEE STANDARDS and its different types.pptx
Introduction to IEEE STANDARDS and its different types.pptxIntroduction to IEEE STANDARDS and its different types.pptx
Introduction to IEEE STANDARDS and its different types.pptx
Ā 
Coefficient of Thermal Expansion and their Importance.pptx
Coefficient of Thermal Expansion and their Importance.pptxCoefficient of Thermal Expansion and their Importance.pptx
Coefficient of Thermal Expansion and their Importance.pptx
Ā 
Extrusion Processes and Their Limitations
Extrusion Processes and Their LimitationsExtrusion Processes and Their Limitations
Extrusion Processes and Their Limitations
Ā 
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
Ā 
What are the advantages and disadvantages of membrane structures.pptx
What are the advantages and disadvantages of membrane structures.pptxWhat are the advantages and disadvantages of membrane structures.pptx
What are the advantages and disadvantages of membrane structures.pptx
Ā 
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur EscortsHigh Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
Ā 
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
Ā 
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptxDecoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
Ā 
MANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLS
MANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLSMANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLS
MANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLS
Ā 
(RIA) Call Girls Bhosari ( 7001035870 ) HI-Fi Pune Escorts Service
(RIA) Call Girls Bhosari ( 7001035870 ) HI-Fi Pune Escorts Service(RIA) Call Girls Bhosari ( 7001035870 ) HI-Fi Pune Escorts Service
(RIA) Call Girls Bhosari ( 7001035870 ) HI-Fi Pune Escorts Service
Ā 
Roadmap to Membership of RICS - Pathways and Routes
Roadmap to Membership of RICS - Pathways and RoutesRoadmap to Membership of RICS - Pathways and Routes
Roadmap to Membership of RICS - Pathways and Routes
Ā 
SPICE PARK APR2024 ( 6,793 SPICE Models )
SPICE PARK APR2024 ( 6,793 SPICE Models )SPICE PARK APR2024 ( 6,793 SPICE Models )
SPICE PARK APR2024 ( 6,793 SPICE Models )
Ā 
the ladakh protest in leh ladakh 2024 sonam wangchuk.pptx
the ladakh protest in leh ladakh 2024 sonam wangchuk.pptxthe ladakh protest in leh ladakh 2024 sonam wangchuk.pptx
the ladakh protest in leh ladakh 2024 sonam wangchuk.pptx
Ā 
HARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICS
HARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICSHARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICS
HARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICS
Ā 
Call Girls Delhi {Jodhpur} 9711199012 high profile service
Call Girls Delhi {Jodhpur} 9711199012 high profile serviceCall Girls Delhi {Jodhpur} 9711199012 high profile service
Call Girls Delhi {Jodhpur} 9711199012 high profile service
Ā 
Architect Hassan Khalil Portfolio for 2024
Architect Hassan Khalil Portfolio for 2024Architect Hassan Khalil Portfolio for 2024
Architect Hassan Khalil Portfolio for 2024
Ā 
College Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
College Call Girls Nashik Nehal 7001305949 Independent Escort Service NashikCollege Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
College Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
Ā 
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130
Ā 

Python.pptx

  • 1. A Quick Tour of Python Akansha Mittal (2K21/AFI/12)
  • 3. Filename, preferred extension is py User Program
  • 4. Interacting with Python Programs ā€¢ Python program communicates its results to user using print ā€¢ Most useful programs require information from users ā€“ Name and age for a travel reservation system ā€¢ Python 3 uses input to read user input
  • 5. input ā€¢ Take as argument a string to print as a prompt ā€¢ Returns the user typed value as a string IN[1]: IN[2]: IN[3]: ( )
  • 6. Types in Python ā€¢ int ā€“ Bounded integers, e.g. 732 or -5 ā€¢ float ā€“ Real numbers, e.g. 3.14 or 2.0 ā€¢ long ā€“ Long integers ā€¢ str ā€“ Strings, e.g. ā€˜helloā€™ or ā€˜Cā€™
  • 8. Type Conversion (Type Cast) ā€¢ Conversion of value of one type to other ā€¢ We are used to int ā†” float conversion in Math ā€“ Integer 3 is treated as float 3.0 when a real number is expected ā€“ Float 3.6 is truncated as 3, or rounded off as 4 for integer contexts ā€¢ Type names are used as type converter functions
  • 9. Type Conversion Examples Note that float to int conversion is truncation, not rounding off
  • 11. Operators ā€¢ Arithmetic ā€¢ Comparison ā€¢ Assignment ā€¢ Logical ā€¢ Bitwise ā€¢ Membership ā€¢ Identity + - * // / % ** == != > < >= <= = += -= *= //= /= %= **= and or not in not in is is not & | ^ ~ >> <<
  • 12. Variables ā€¢ A name associated with an object ā€¢ Assignment used for binding m = 64; c = ā€˜Acadsā€™; f = 3.1416; ā€¢ Variables can change their bindings f = 2.7183; 64 Acads 3.1416 2.7183 m c f
  • 13. Assignment Statement ā€¢ A simple assignment statement Variable = Expression; ā€¢ Computes the value (object) of the expression on the right hand side expression (RHS) ā€¢ Associates the name (variable) on the left hand side (LHS) with the RHS value ā€¢ = is known as the assignment operator.
  • 14. Multiple Assignments ā€¢ Python allows multiple assignments x, y = 10, 20 ā€¢ Evaluation of multiple assignment statement: ā€“ All the expressions on the RHS of the = are first evaluated before any binding happens. ā€“ Values of the expressions are bound to the corresponding variable on the LHS. x, y = 10, 20 x, y = y+1, x+1 Binds x to 10 and y to 20 x is bound to 21 and y to 11 at the end of the program
  • 16. Binary Operations Op Meaning Example Remarks + Addition 9+2 is 11 9.1+2.0 is 11.1 - Subtraction 9-2 is 7 9.1-2.0 is 7.1 * Multiplication 9*2 is 18 9.1*2.0 is 18.2 / Division 9/2 is 4.25 In Python3 9.1/2.0 is 4.55 Real div. // Integer Division 9//2 is 4 % Remainder 9%2 is 1
  • 17. The // operator ā€¢ Also referred to as ā€œinteger divisionā€ ā€¢ Result is a whole integer (floor of real division) ā€“ But the type need not be int ā€“ the integral part of the real division ā€“ rounded towards minus infinity (āˆ’āˆž) ā€¢ Examples 9//4 is 2 (-1)//2 is -1 (-1)//(-2) is 0 1//2 is 0 1//(-2) is -1 9//4.5 is 2.0
  • 18. The % operator ā€¢ The remainder operator % returns the remainder of the result of dividing its first operand by its second. 9%4 is 1 (-1)%2 is 1 (-1)//(-2) is 0 9%4.5 is 0.0 1%(-2) is 1 1%0.6 is 0.4 Ideally: x == (x//y)*y + x %y
  • 19. Conditional Statements ā€¢ In daily routine ā€“If it is very hot, I will skip exercise. ā€“If there is a quiz tomorrow, I will first study and then sleep. Otherwise I will sleep now. ā€“If I have to buy coffee, I will go left. Else I will go straight.
  • 20. if-else statement ā€¢ Compare two integers and print the min. 1. Check if x is less than y. 2. If so, print x 3. Otherwise, print y. if x < y: print (x) else: print (y) print (ā€˜is the minimumā€™)
  • 21. x,y = 6,10 if x < y: print (x) else: print (y) print (ā€˜is the minā€™) x y 6 10 Run the program Output 6 Indentation ā€¢ Indentation is important in Python ā€“ grouping of statement (block of statements) ā€“ no explicit brackets, e.g. { }, to group statements
  • 22. if statement (no else!) ā€¢ General form of the if statement ā€¢ Execution of if statement ā€“ First the expression is evaluated. ā€“ If it evaluates to a true value, then S1 is executed and then control moves to the S2. ā€“ If expression evaluates to false, then control moves to the S2 directly. if boolean-expr : S1 S2 S1 S2
  • 23. if-else statement ā€¢ General form of the if-else statement ā€¢ Execution of if-else statement ā€“ First the expression is evaluated. ā€“ If it evaluates to a true value, then S1 is executed and then control moves to S3. ā€“ If expression evaluates to false, then S2 is executed and then control moves to S3. ā€“ S1/S2 can be blocks of statements! if boolean-expr : S1 else: S2 S3 S2 S1 S3
  • 24. Nested if, if-else if a <= b: if a <= c: ā€¦ else: ā€¦ else: if b <= c) : ā€¦ else: ā€¦
  • 25. Elif ā€¢ A special kind of nesting is the chain of if- else-if-else-ā€¦ statements ā€¢ Can be written elegantly using if-elif-..-else if cond1: s1 elif cond2: s2 elif cond3: s3 elif ā€¦ else last-block-of-stmt if cond1: s1 else: if cond2: s2 else: if cond3: s3 else: ā€¦
  • 26. Summary of if, if-else ā€¢ if-else, nested if's, elif. ā€¢ Multiple ways to solve a problem ā€“issues of readability, maintainability ā€“and efficiency
  • 27. Quiz ā€¢ What is the value of expression: a) Run time crash/error b) I donā€™t know / I donā€™t care c) False d) True (5<2) and (3/0 > 1) The correct answer is False
  • 28. Short-circuit Evaluation ā€¢ Do not evaluate the second operand of binary short-circuit logical operator if the result can be deduced from the first operand ā€“ Also applies to nested logical operators not( (2>5) and (3/0 > 1) ) or (4/0 < 2) Evaluates to true false false true true
  • 29. 3 Factors for Expr Evaluation ā€¢ Precedence ā€“ Applied to two different class of operators ā€“ + and *, - and *, and and or, ā€¦ ā€¢ Associativity ā€“ Applied to operators of same class ā€“ * and *, + and -, * and /, ā€¦ ā€¢ Order ā€“ Precedence and associativity identify the operands for each operator ā€“ Not which operand is evaluated first ā€“ Python evaluates expressions from left to right ā€“ While evaluating an assignment, the right-hand side is evaluated before the left-hand side.
  • 30. ā€¢ Representation of real numbers in a computer can not be exact ā€“ Computers have limited memory to store data ā€“ Between any two distinct real numbers, there are infinitely many real numbers. ā€¢ On a typical machine running Python, there are 53 bits of precision available for a Python float Caution about Using Floats
  • 31. ā€¢ Because of the approximations, comparison of floats is not exact. ā€¢ Solution? ā€¢ Instead of x == y use abs(x-y) <= epsilon where epsilon is a suitably chosen small value Comparing Floats
  • 33. Printing Multiplication Table 5 X 1 = 5 5 X 2 = 10 5 X 3 = 15 5 X 4 = 20 5 X 5 = 25 5 X 6 = 30 5 X 7 = 35 5 X 8 = 40 5 X 9 = 45 5 X 10 = 50
  • 34. Programā€¦ n = int(input('Enter a number: ')) print (n, 'X', 1, '=', n*1) print (n, 'X', 2, '=', n*2) print (n, 'X', 3, '=', n*3) print (n, 'X', 4, '=', n*4) print (n, 'X', 5, '=', n*5) print (n, 'X', 6, '=', n*6) ā€¦. Too much repetition! Can I avoid it?
  • 35. Print n X i = n*i i = i+1 Input n i = 1 i <=10 TRUE FALSE Printing Multiplication Table Stop Loop Loop Entry Loop Exit
  • 36. Printing Multiplication Table n = int(input('n=? ')) i = 1 while (i <= 10) : print (n ,'X', i, '=', n*i) i = i + 1 print ('doneā€˜) Print n x i = ni i = i+1 Input n i = 1 TRUE i <=10 FALSE Stop
  • 37. While Statement 1. Evaluate expression 2. If TRUE then a) execute statement1 b) goto step 1. 3. If FALSE then execute statement2. while (expression): S1 S2 FALSE TRUE S1 expression S2
  • 38. For Loop ā€¢ Print the sum of the reciprocals of the first 100 natural numbers. rsum=0.0# the reciprocal sum # the for loop for i in range(1,101): rsum = rsum + 1.0/i print ('sum is', rsum)
  • 39. For loop in Python ā€¢ General form for variable in sequence: stmt
  • 40. range ā€¢ range(s, e, d) ā€“generates the list: [s, s+d, s+2*d, ā€¦, s+k*d] where s+k*d < e <= s+(k+1)*d ā€¢ range(s, e) is equivalent to range(s, e, 1) ā€¢ range(e) is equivalent to range(0, e) Exercise: What if d is negative? Use python interpreter to find out.
  • 41. # print all odd numbers < 10 i = 1 while i <= 10: if i%2==0: # even continue print (i, end=ā€˜ ā€˜) i = i+1 Quiz ā€¢ What will be the output of the following program
  • 42. # print all odd numbers < 10 i = 1 while i <= 10: if i%2==0: # even continue print (i, end=ā€˜ ā€˜) i = i+1 Continue and Update Expr ā€¢ Make sure continue does not bypass update- expression for while loops i is not incremented when even number encountered. Infinite loop!!
  • 44. Parts of a function Input Output f
  • 45. x = max(6, 4) def max (a, b): ā€˜ā€™ā€™return maximum among a and bā€™ā€™ā€™ if (a > b): return a else: return b keyword Function Name 2 arguments a and b (formal args) Body of thefunction, indented w.r.t the def keyword Documentation comment Call to the function. Actual args are 6 and 4.
  • 46. Keyword Arguments def printName(first, last, initials) : if initials: print (first[0] + '. ' + last[0] + '.') else: print (first, last) Call Output printName('Acads', 'Institute', False) Acads Institute printName('Acads', 'Institute', True) A. I. printName(last='Institute', initials=False, first='Acads') Acads Institute printName('Acads', initials=True, last='Institute') A. I. Note use of [0] to get the first character of a string. More on this later.
  • 47. Keyword Arguments ā€¢ Parameter passing where formal is bound to actual using formal's name ā€¢ Can mix keyword and non-keyword arguments ā€“ All non-keyword arguments precede keyword arguments in the call ā€“ Non-keyword arguments are matched by position (order is important) ā€“ Order of keyword arguments is not important
  • 48. Default Values def printName(first, last, initials=False) : if initials: print (first[0] + '. ' + last[0] + '.') else: print (first, last) Call Output printName('Acads', 'Institute') Acads Institute printName(first='Acads', last='Institute', initials=True) A. I. printName(last='Institute', first='Acads') Acads Institute printName('Acads', last='Institute') Acads Institute Note the use of ā€œdefaultā€ value
  • 49. Default Values ā€¢ Allows user to call a function with fewer arguments ā€¢ Useful when some argument has a fixed value for most of the calls ā€¢ All arguments with default values must be at the end of argument list ā€“ non-default argument can not follow default argument
  • 50. Globals ā€¢ Globals allow functions to communicate with each other indirectly ā€“ Without parameter passing/return value ā€¢ Convenient when two seemingly ā€œfar-apartā€ functions want to share data ā€“ No direct caller/callee relation ā€¢ If a function has to update a global, it must re- declare the global variable with global keyword.
  • 51. Globals PI = 3.14 def perimeter(r): return 2 * PI * r def area(r): return PI * r * r def update_pi(): global PI PI = 3.14159 defines PI to be of float type with value 3.14. PI can be used across functions. Any change to PI in update_pi will be visible to all due to the use of global. >>> print(area (100)) 31400.0 >>> print(perimeter(10)) 62.800000000000004 >>> update_pi() >>> print(area(100)) 31415.999999999996 >>> print(perimeter(10)) 62.832
  • 52. Programming with Python T U E P L S L I S S T S T N R I G S
  • 53. Strings ā€¢ Strings in Python have type str ā€¢ They represent sequence of characters ā€“ Python does not have a type corresponding to character. ā€¢ Strings are enclosed in single quotes(') or double quotes(ā€œ) ā€“ Both are equivalent ā€¢ Backslash () is used to escape quotes and special characters
  • 54. Strings ā€¢ More readable when print is used
  • 55. Length of a String ā€¢ len function gives the length of a string n is a single character: the special character representing newline
  • 56. Concatenate and Repeat ā€¢ In Python, + and * operations have special meaning when operating on strings ā€¢ + is used for concatenation of (two) strings ā€¢ * is used to repeat a string, an int number of time ā€¢ Function/Operator Overloading
  • 58. Indexing ā€¢ Strings can be indexed ā€¢ First character has index 0
  • 59. Indexing ā€¢ Negative indices start counting from the right ā€¢ Negatives indices start from -1 ā€¢ -1 means last, -2 second last, ...
  • 60. Indexing ā€¢ Using an index that is too large or too small results in ā€œindex out of rangeā€ error
  • 61. Slicing ā€¢ To obtain a substring ā€¢ s[start:end] means substring of s starting at index start and ending at index end-1 ā€¢ s[0:len(s)] is same as s ā€¢ Both start and end are optional ā€“ If start is omitted, it defaults to 0 ā€“ If end is omitted, it defaults to the length of string ā€¢ s[:] is same as s[0:len(s)], that is same as s
  • 63. More Slicing A c a d s 0 1 2 3 4 -5 -4 -3 -2 -1 Understanding Indices for slicing 5
  • 64. Out of Range Slicing ā€¢ Out of range indices are ignored for slicing ā€¢ when start and end have the same sign, if start >=end, empty slice is returned Why? A c a d s 0 1 2 3 4 -5 -4 -3 -2 -1
  • 65. Tuples ā€¢ A tuple consists of a number of values separated by commas ā€¢ Empty and Singleton Tuples
  • 66. Nested Tuples ā€¢ Tuples can be nested ā€¢ Note that course tuple is copied into student. ā€“ Changing course does not affect student
  • 67. Length of a Tuple ā€¢ len function gives the length of a tuple
  • 68. More Operations on Tuples ā€¢ Tuples can be concatenated, repeated, indexed and sliced
  • 69. Unpacking Sequences ā€¢ Strings and Tuples are examples of sequences ā€“ Indexing, slicing, concatenation, repetition operations applicable on sequences ā€¢ Sequence Unpacking operation can be applied to sequences to get the components ā€“ Multiple assignment statement ā€“ LHS and RHS must have equal length
  • 71. Lists ā€¢ Ordered sequence of values ā€¢ Written as a sequence of comma-separated values between square brackets ā€¢ Values can be of different types ā€“ usually the items all have the same type
  • 72. Lists ā€¢ List is also a sequence type ā€“ Sequence operations are applicable
  • 73. Lists ā€¢ List is also a sequence type ā€“ Sequence operations are applicable Repetition ( )
  • 74. More Operations on Lists ā€¢ L.append(x) ā€¢ L.extend(seq) ā€¢ L.insert(i, x) ā€¢ L.remove(x) ā€¢ L.pop(i) ā€¢ L.pop() ā€¢ L.index(x) ā€¢ L.count(x) ā€¢ L.sort() ā€¢ L.reverse() x is any value, seq is a sequence value (list, string, tuple, ā€¦), i is an integer value
  • 75. Mutable and Immutable Types ā€¢ Tuples and List types look very similar ā€¢ However, there is one major difference: Lists are mutable ā€“ Contents of a list can be modified ā€¢ Tuples and Strings are immutable ā€“ Contents can not be modified
  • 76. Summary of Sequences Operation Meaning seq[i] i-th element of the sequence len(seq) Length of the sequence seq1 + seq2 Concatenate the two sequences num*seq seq*num Repeat seq num times seq[start:end] slice starting from start, and ending at end-1 e in seq True if e is present is seq, False otherwise e not in seq True if e is not present is seq, False otherwise for e in seq Iterate over all elements in seq (e is bound to one element per iteration) Sequence types include String, Tuple and List. Lists are mutable, Tuple and Strings immutable.
  • 77. Programming with Python Sets and Dictionaries
  • 78. Sets ā€¢ An unordered collection with no duplicate elements ā€¢ Supports ā€“ membership testing ā€“ eliminating duplicate entries ā€“ Set operations: union, intersection, difference, and symmetric difference.
  • 79. Sets Create a set from a sequence { }
  • 80. Set Operations { } { } { } { } { }
  • 81. Dictionaries ā€¢ Unordered set of key:value pairs, ā€¢ Keys have to be unique and immutable ā€¢ Key:value pairs enclosed inside curly braces {...} ā€¢ Empty dictionary is created by writing {} ā€¢ Dictionaries are mutable ā€“add new key:value pairs, ā€“change the pairing ā€“delete a key (and associated value)
  • 82. Operations on Dictionaries Operation Meaning len(d) Number of key:value pairs in d d.keys() List containing the keys in d d.values() List containing the values in d k in d True if key k is in d d[k] Value associated with key k in d d.get(k, v) If k is present in d, then d[k] else v d[k] = v Map the value v to key k in d (replace d[k] if present) del d[k] Remove key k (and associated value) from d for k in d Iterate over the keys in d
  • 85. Operations on Dictionaries # Remember: for ... in iterates over keys only # Sort values in a list
  • 86. Dictionary Construction ā€¢ The dict constructor: builds dictionaries directly from sequences of key-value pairs
  • 88. File I/O ā€¢ Files are persistent storage ā€¢ Allow data to be stored beyond program lifetime ā€¢ The basic operations on files are ā€“ open, close, read, write ā€¢ Python treat files as sequence of lines ā€“ sequence operations work for the data read from files
  • 89. File I/O: open and close open(filename, mode) ā€¢ While opening a file, you need to supply ā€“ The name of the file, including the path ā€“ The mode in which you want to open a file ā€“ Common modes are r (read), w (write), a (append) ā€¢ Mode is optional, defaults to r ā€¢ open(..) returns a file object ā€¢ close() on the file object closes the file ā€“ finishes any buffered operations
  • 90. File I/O: Example ā€¢ Do some writing ā€¢ How to do it? ā€¢ see the next few slides
  • 91. File I/O: read, write and append ā€¢ Reading from an open file returns the contents of the file ā€“ as sequence of lines in the program ā€¢ Writing to a file ā€“ IMPORTANT: If opened with mode 'w', clears the existing contents of the file ā€“ Use append mode ('a') to preserve the contents ā€“ Writing happens at the end
  • 94. File I/O: Examples Note empty line due to 'n' ( )
  • 95. File I/O: Examples Note the use of for ... in for sequence ] ( )
  • 96. File I/O: Examples ( ) ( ) ( )
  • 98. OOP Terminology ā€¢ Class ā€¢ Class variable ā€¢ Data member ā€¢ Function overloading ā€¢ Instance variable ā€¢ Inheritance ā€¢ Instance ā€¢ Instantiation ā€¢ Method ā€¢ Object ā€¢ Operator overloading
  • 99. Class class Employee: 'Common base class for all employees' empCount = 0 def __init__(self, name, salary): self.name = name self.salary = salary Employee.empCount += 1 def displayCount(self): print "Total Employee %d" % Employee.empCount def displayEmployee(self): print "Name : ", self.name, ", Salary: ", self.salary "This would create first object of Employee class" emp1 = Employee("Zara", 2000) "This would create second object of Employee class" emp2 = Employee("Manni", 5000) emp1.displayEmployee() emp2.displayEmployee() print "Total Employee %d" % Employee.empCount
  • 100. Class Inheritance class Parent: # define parent class parentAttr = 100 def __init__(self): print "Calling parent constructor" def parentMethod(self): print 'Calling parent method' def setAttr(self, attr): Parent.parentAttr = attr def getAttr(self): print "Parent attribute :", Parent.parentAttr class Child(Parent): # define child class def __init__(self): print "Calling child constructor" def childMethod(self): print 'Calling child method' c = Child() # instance of child c.childMethod() # child calls its method c.parentMethod() # calls parent's method c.setAttr(200) # again call parent's method c.getAttr() # again call parent's method
  • 101. Overriding Methods class Parent: # define parent class def myMethod(self): print 'Calling parent method' class Child(Parent): # define child class def myMethod(self): print 'Calling child method' c = Child() # instance of child c.myMethod() # child calls overridden method
  • 102. Overloading Operators class Vector: def __init__(self, a, b): self.a = a self.b = b def __str__(self): return 'Vector (%d, %d)' % (self.a, self.b) def __add__(self,other): return Vector(self.a + other.a, self.b + other.b) v1 = Vector(2,10) v2 = Vector(5,-2) print v1 + v2
  • 103. Data Hiding An object's attributes may or may not be visible outside the class definition. You need to name attributes with a double underscore prefix, and those attributes then are not be directly visible to outsiders.