Python 4 HPC
Python 4 HPC
Amey Karkare
Dept. of CSE
IIT Kanpur
Welcome Python Programming
Acknowledgements
MS Office clip art, various websites and
images
The images/contents are used for
teaching purpose and for fun. The
copyright remains with the original
creator. If you suspect a copyright
violation, bring it to my notice and I will
remove that image/content.
http://www.cse.iitk.ac.in/~karkare
Programming
The Programming Cycle for Python
Programming
Run
with some input
Write/Edit
OK?
NO
YES
YES
NO More
Inputs?
Programming
User Program
Filename, preferred extension is py
Programming
IN[1]: Python Shell Prompt
IN[2]:
User Commands
IN[3]: (Statements)
IN[4]: ( )
Outputs
Programming
input
• Take as argument a string to print as a prompt
• Returns the user typed value as a string
– details of how to process user string later
IN[1]:
IN[2]: ( )
IN[3]:
Programming
Elements of Python
• A Python program is a sequence of definitions
and commands (statements)
• Commands manipulate objects
• Each object is associated with a Type
• Type:
– A set of values
– A set of operations on these values
• Expressions: An operation (combination of
objects and operators)
Programming
Types in Python
• int
– Bounded integers, e.g. 732 or -5
• float
– Real numbers, e.g. 3.14 or 2.0
• long
– Long integers with unlimited precision
• str
– Strings, e.g. ‘hello’ or ‘C’
Programming
Types in Python
• Scalar
– Indivisible objects that do not have internal
structure
– int (signed integers), float (floating point), bool
(Boolean), NoneType
• NoneType is a special type with a single value
• The value is called None
• Non-Scalar
– Objects having internal structure
– str (strings)
Programming
Example of Types
Programming
Type Conversion (Type Cast)
Programming
Type Conversion Examples
Note that float to int conversion
is truncation, not rounding off
Programming
Type Conversion and Input
Programming
Operators
• Arithmetic + - * // / % **
Programming
Variables
• A name associated with an m
object 64
• Assignment used for binding Acads
m = 64; c
3.1416
c = ‘Acads’;
f = 3.1416; f
Programming
Multiple Assignments
• Python allows multiple assignments
x, y = 10, 20 Binds x to 10 and y to 20
Programming
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
Programming
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
Programming
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
Programming
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.
Programming
if-else statement
• Compare two integers and print the min.
Programming
Indentation
• Indentation is important in Python
– grouping of statement (block of statements)
– no explicit brackets, e.g. { }, to group statements
x,y = 6,10 Run
x the program
y
if x < y: 6 10
print (x)
else:
print (y) ed Output
i p p
sk the min’)
print (‘is 6
Programming
if statement (no else!)
• General form of the if statement
e
if boolean-expr : tru
fals
S1
e
S1
S2
• Execution of if statement S2
– 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.
Programming
if-else statement
• General form of the if-else statement
if boolean-expr : rt u
e
fa
S1
ls
e
else: S1 S2
S2
S3 S3
• 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!
Programming
Nested if, if-else
if a <= b:
if a <= c:
…
else:
…
else:
if b <= c) :
…
else:
…
Programming
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: if cond1:
s1 s1
else: elif cond2:
if cond2: s2
s2 elif cond3:
else: s3
if cond3: elif …
s3 else
else: last-block-of-stmt
…
Programming
Summary of if, if-else
• if-else, nested if's, elif.
• Multiple ways to solve a problem
–issues of readability,
maintainability
–and efficiency
Programming
Class Quiz
• What is the value of expression:
(5<2) and (3/0 > 1)
c) False
The correct answer is
False
d) True
Programming
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
Programming
Caution about Using Floats
• 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
Programming
Caution about Using Floats
• The value stored internally for the decimal
number 0.1 is the binary fraction
0.00011001100110011001100110011001100110011001100110011010
Programming
Programming using Python
Loops
Python Programming
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
Python Programming
Program…
n = int(input('Enter a Too
number:
much '))
print (n, 'X', 1, '=', n*1)
repetition!
print (n, 'X', 2, '=', n*2)
Can I avoid
print (n, 'X', 3, '=', n*3)it?
print (n, 'X', 4, '=', n*4)
print (n, 'X', 5, '=', n*5)
print (n, 'X', 6, '=', n*6)
….
Python Programming
Printing Multiplication Table
Loop Exit
i <=10
TRUE FALSE
Loop
Python Programming
Printing Multiplication Table
Input n
i=1
TRUE
i <=10
FALSE n = int(input('n=? '))
i=1
Print n x i = ni Stop
i = i+1
Python Programming
While Statement
while (expression):
S1 expression
FALSE
S2
TRUE
S1 S2
1. Evaluate expression
2. If TRUE then
a) execute statement1
b) goto step 1.
3. If FALSE then execute statement2.
Python Programming
For Loop
• Print the sum of the reciprocals of the
first 100 natural numbers.
Python Programming
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.
Python Programming
Quiz
• What will be the output of the following
program
f(unctions)
Programming, Functions
Parts of a function
Input
In[3] : help(max)
Help on function max in module __main__:
max(a, b)
return maximum among a and b
Oct 15, 2023 Programming, Functions
Keyword Arguments
Note use of [0]
def printName(first, last, initials) : to get the first
if initials: character of a
string. More on
print (first[0] + '. ' + last[0] + '.') this later.
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.
S T R I NGS
T UP L E S
L I S T S
Programming
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
Oct 15, 2023 Programming
Strings
\n is a single character:
the special character
representing newline
Oct 15, 2023 Programming
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
( )
Repetition
( )
Esc101, Strings
Sets
• An unordered collection with no duplicate
elements
• Supports
– membership testing
– eliminating duplicate entries
– Set operations: union, intersection, difference, and
symmetric difference.
{ }
{ }
{ }
{ }
{ }
{ }
File I/O
Programming
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
Programming
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
Programming
File I/O: Example
• Do some writing
• How to do it?
• see the next few slides
Programming
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
Programming
File I/O: Examples
Programming
File I/O: Examples
( )
( )
Programming
File I/O: Examples
( )
Programming
File I/O: Examples
Note the use of for ... in
for sequence
( )
]
Programming
File I/O: Examples
( )
( )
( )
Programming
Programming using Python
Programming
Modules Example
fib.py - C:\
Programming
Modules Example
Programming
Importing ALL Functions
• To import all functions from a module, in the current
symbol table
Programming
__main__ in Modules
• When you run a module on the command line with
python fib.py <arguments>
the code in the module will be executed, just as if
you imported it, but with the __name__ set to
"__main__".
• By adding this code at the end of your module
if __name__ == "__main__":
... # Some code here
you can make the file usable as a script as well as an
importable module
Programming
__main__ in Modules
if __name__ == "__main__":
import sys
print (fib_iter(int(sys.argv[1])))
• This code parses the command line only if the
module is executed as the “main” file:
$ python fib.py 10
55
• If the module is imported, the code is not run:
>>> import fib
>>>
Programming
Package
• A Python package is a collection of Python modules.
• Another level of organization.
• Packages are a way of structuring Python’s module
namespace by using dotted module names.
– The module name A.B designates a submodule
named B in a package named A.
– The use of dotted module names saves the authors of
multi-module packages like NumPy or Pillow from having
to worry about each other’s module names.
Programming
A sound Package
https://docs.python.org/3/tutorial/modules.html
Programming
A sound Package
https://docs.python.org/3/tutorial/modules.html
https://docs.python.org/3/tutorial/
modules.html
Programming
Importing Modules from Packages
import sound.effects.echo
sound.effects.echo.echofilter(
input, output,
delay=0.7, atten=4
)
Programming
Importing Modules from Packages
from sound.effects import echo
• This also loads the submodule echo
• Makes it available without package prefix
• It can be used as:
echo.echofilter(
input, output,
delay=0.7, atten=4
)
Programming
Importing Modules from Packages
from sound.effects.echo import echofilter
echofilter(input, output,
delay=0.7, atten=4)
Programming
Popular Packages
• pandas, numpy, scipy, matplotlib, …
• Provide a lot of useful functions
Programming