Python - Programming
Python - Programming
• No one language is
better than all
others.
• The ‘best’ language
depends on the task
you are using it for
and your personal
preference.
Versions of Python
• There are currently two versions of Python in use;
Python 2 and Python 3.
• Python 3 is not backward compatible with Python 2.
• A lot of the imported modules were only available in
Python 2 for quite some time, leading to a slow
adoption of Python 3. However, this not really an
issue anymore.
• Support for Python 2 will ended in 2020. But
updates are still given
The Anaconda IDE…
Write/Edit
OK?
NO
YES
YES
NO More
Inputs?
10
3/28/23 Programming
User Program
Filename, preferred extension is py
11
3/28/23 Programming
IN[1]: Python Shell Prompt
IN[2]:
User Commands
IN[3]: (Statements)
IN[4]: ( )
Outputs
13
3/28/23 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]:
3/28/23 Programming 14
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)
15
3/28/23 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’
16
3/28/23 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)
17
3/28/23 Programming
Example of Types
18
3/28/23 Programming
Type Conversion (Type Cast)
19
3/28/23 Programming
Type Conversion Examples
Note that float to int conversion
is truncation, not rounding off
20
3/28/23 Programming
Type Conversion and Input
ii
21
3/28/23 Programming
22
3/28/23 Programming
The print() function
• A function is a separate part of the computer code
able to:
• cause some effect (e.g., send text to the terminal,
create a file, draw an image, play a sound, etc.); this
is something completely unheard of in the world of
mathematics;
• evaluate a value (e.g., the square root of a value or
the length of a given text) and return it as the
function's result; this is what makes Python
functions the relatives of mathematical concepts.
23
Welcome Python Programming
The print() function
• The function name (print in this case) along with the
parentheses and argument(s), forms the function
invocation.
• The print() function has two keyword arguments
that you can use for keyword arguments. The first is
called end.
– a keyword argument consists of three elements: a
keyword identifying the argument (end here); an equal
sign (=); and a value assigned to that argument;
– any keyword arguments have to be put after the last
positional argument (this is very important)
24
Welcome Python Programming
The print() function
print("My name is", "Python.", end=" ")
print("Monty Python.")
Output:
My name is Python. Monty Python.
25
Welcome Python Programming
The print() function
• print() function separates its outputted
arguments with spaces using keyword
argument : sep (as in separator).
print("My", "name", "is", "Monty", "Python.",
sep="-")
Output
My-name-is-Monty-Python.
• the sep argument's value may be an empty
string, too
26
Welcome Python Programming
The print() function
• Example: using the sep and end keywords, to
match the expected output
Output
Programming***Essentials***in...Python
• print("Programming","Essentials","in",
sep="***", end="...")
• print("Python")
27
Welcome Python Programming
Variables
• Variables in python can contain alphanumerical characters and
some special characters.
• By convention, it is common to have variable names that start
with lower case letters and have class names beginning with a
capital letter; but you can do whatever you want.
• Some keywords are reserved and cannot be used as variable
names due to them serving an in-built Python function; i.e. and,
continue, break. Your IDE will let you know if you try to use one
of these.
• Python is dynamically typed; the type of the variable is derived
from the value it is assigned.
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
30
3/28/23 Programming
How to use a variable
• You're allowed to use as many variable
declarations as you need to achieve your goal,
like this:
var = 1
account_balance = 1000.0
client_name = “John Doe”
print(var, account_balance, client_name)
print(var)
31
Welcome Python Programming
Multiple Assignments
• Python allows multiple assignments
x, y = 10, 20 Binds x to 10 and y to 20
34
03/28/2023 Programming
Operators
• Arithmetic + - * // / % **
35
3/28/23 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
36
03/28/2023 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
37
03/28/2023 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
38
03/28/2023 Programming
Exponentiation and Multiplication
√ (x) = x(½)
Welcome Python Programming
c = √ a2 + b2 40
Exercise
• Write a program that reads a float value, puts
it into a variable named x, and prints the value
of a variable named y:
y = 3x3 - 2x2 + 3x - 1
41
Welcome Python 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. 42
3/28/23 Programming
if-else statement
• Compare two integers and print the min.
43
3/28/23 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
print (‘is i pp
sk the min’) 6 44
3/28/23 Programming
if statement (no else!)
• General form of the if statement
e
if boolean-expr : tru
fals
e
S1
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.
45
3/28/23 Programming
if-else statement
• General form of the if-else statement
if boolean-expr : tru
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! 46
3/28/23 Programming
Nested if, if-else
if a <= b:
if a <= c:
…
else:
…
else:
if b <= c) :
…
else:
…
47
3/28/23 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
…
48
3/28/23 Programming
Summary of if, if-else
• if-else, nested if's, elif.
• Multiple ways to solve a problem
–issues of readability,
maintainability
–and efficiency
49
3/28/23 Programming
Class Quiz
• What is the value of expression:
(5<2) and (3/0 > 1)
d) True
50
3/28/23 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
54
3/28/23 Programming
Caution about Using Floats
• The value stored internally for the decimal
number 0.1 is the binary fraction
0.00011001100110011001100110011001100110011001100110011010
56
3/28/23 Programming
Exercise
• Spathiphyllum, more commonly known as a peace lily or white sail
plant, is one of the most popular indoor houseplants that filters out
harmful toxins from the air. Some of the toxins that it neutralizes
include benzene, formaldehyde, and ammonia.
• Imagine that your computer program loves these plants. Whenever
it receives an input in the form of the word Spathiphyllum, it
involuntarily shouts to the console the following string:
"Spathiphyllum is the best plant ever!“
Write a program that utilizes the concept of conditional execution,
takes a string as input, and:
• prints the sentence "Yes - Spathiphyllum is the bestplant ever!" to
the screen if the inputted string is "Spathiphyllum" (upper-case - s)
• prints "No, I want a big Spathiphyllum!" if the inputted string is
"spathiphyllum" (lower-case)
• prints "Spathiphyllum! Not [input]!" otherwise. Note: [input] is the
string taken as input. 57
Welcome Python Programming
Programming using Python
Loops
58
3/28/23 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
59
3/28/23 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)
….
60
3/28/23 Python Programming
Printing Multiplication Table
Loop Exit
i <=10
TRUE FALSE
Loop 61
3/28/23 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
62
3/28/23 Python Programming
While Statement
while (expression):
S1 FALSE
expression
S2
TRUE
S1 S2
1. Evaluate expression
2. If TRUE then
a) execute statement1
b) goto step 1.
3. If FALSE then execute statement2.
63
3/28/23 Python Programming
For Loop
• Print the sum of the reciprocals of the
first 100 natural numbers.
65
3/28/23 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. 66
3/28/23 Python Programming
Quiz
• What will be the output of the following
program
f(unctions)
70
3/28/23 Programming, Functions
Parts of a function
Input
71
3/28/23 Output
Programming, Functions
def max (a, b):
‘’’return maximum among a and b’’’
keyword if (a > b):
return a 2 arguments
else: a and b
Function Name return b (formal args)
In[3] : help(max)
Help on function max in module __main__:
max(a, b)
return maximum among a and b
73
3/28/23 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.
74
3/28/23 Programming, Functions
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
75
3/28/23 Programming, Functions
Default Values
def printName(first, last, initials=False) :
if initials:
print (first[0] + '. ' + last[0] + '.')
Note the use
else: of “default”
value
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
76
3/28/23 Programming, Functions
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
77
3/28/23 Programming, Functions
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.
78
3/28/23 Programming, Functions
Globals
PI = 3.14 >>> print(area (100))
def perimeter(r): 31400.0
return 2 * PI * r >>> print(perimeter(10))
def area(r): 62.800000000000004
return PI * r * r >>> update_pi()
def update_pi(): >>> print(area(100))
global PI 31415.999999999996
PI = 3.14159 >>> print(perimeter(10))
62.832
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 79
all due to the use of global.
3/28/23 Programming, Functions
Programming with Python
S T R I NGS
T UP L E S
L I S T S
80
3/28/23 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
81
3/28/23 Programming
Strings
82
3/28/23 Programming
Length of a String
• len function gives the length of a string
\n is a single character:
the special character
representing newline 83
3/28/23 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
84
3/28/23 Programming
Concatenate and Repeat
85
3/28/23 Programming
Indexing
• Strings can be indexed
• First character has index 0
86
3/28/23 Programming
Indexing
• Negative indices start counting from the right
• Negatives indices start from -1
• -1 means last, -2 second last, ...
87
3/28/23 Programming
Indexing
• Using an index that is too large or too small
results in “index out of range” error
88
3/28/23 Programming
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
89
3/28/23 Programming
Slicing
90
3/28/23 Programming
More Slicing
92
3/28/23 Programming
Tuples
• A tuple consists of a number of values
separated by commas
93
3/28/23 Programming
Nested Tuples
• Tuples can be nested
94
3/28/23 Programming
Length of a Tuple
• len function gives the length of a tuple
95
3/28/23 Programming
More Operations on Tuples
• Tuples can be concatenated, repeated,
indexed and sliced
96
3/28/23 Programming
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
97
3/28/23 Programming
Unpacking Sequences
( )
98
3/28/23 Programming
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
99
3/28/23 Programming
Lists
• List is also a sequence type
– Sequence operations are applicable
100
3/28/23 Programming
Lists
• List is also a sequence type
– Sequence operations are applicable
Repetition
( )
101
3/28/23 Programming
More Operations on Lists
• L.append(x) • L.pop()
• L.extend(seq) • L.index(x)
• L.insert(i, x) • L.count(x)
• L.remove(x) • L.sort()
• L.pop(i) • L.reverse()
x is any value, seq is a sequence value (list, string, tuple, …),
i is an integer value
102
3/28/23 Programming
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
103
3/28/23 Programming
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
105
3/28/23 Programming
Programming with Python
106
3/28/23 Esc101, Strings
Sets
• An unordered collection with no duplicate
elements
• Supports
– membership testing
– eliminating duplicate entries
– Set operations: union, intersection, difference, and
symmetric difference.
107
3/28/23 Programming
Sets
{ }
108
3/28/23 Programming
Set Operations
{ }
{ }
{ }
{ }
{ }
109
3/28/23 Programming
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)
110
3/28/23 Programming
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
111
3/28/23 Programming
Operations on Dictionaries
112
3/28/23 Programming
Operations on Dictionaries
113
3/28/23 Programming
Operations on Dictionaries
114
3/28/23 Programming
Dictionary Construction
• The dict constructor: builds dictionaries
directly from sequences of key-value pairs
115
3/28/23 Esc101, Strings
Programming with Python
File I/O
116
3/28/23 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
117
3/28/23 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
118
3/28/23 Programming
File I/O: Example
• Do some writing
• How to do it?
• see the next few slides
119
3/28/23 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
120
3/28/23 Programming
File I/O: Examples
121
3/28/23 Programming
File I/O: Examples
( )
( )
122
3/28/23 Programming
File I/O: Examples
( )
123
3/28/23 Programming
File I/O: Examples
Note the use of for ... in
for sequence
( )
]
124
3/28/23 Programming
File I/O: Examples
( )
( )
( )
125
3/28/23 Programming
Programming using Python
126
Welcome Python Programming
Modules
• As program gets longer, need to organize them for
easier access and easier maintenance.
• Reuse same functions across programs without
copying its definition into each program.
• Python allows putting definitions in a file
– use them in a script or in an interactive instance of the
interpreter
• Such a file is called a module
– definitions from a module can be imported into other
modules or into the main module
127
3/28/23 Programming
Modules
• A module is a file containing Python
definitions and statements.
• The file name is the module name with the
suffix .py appended.
• Within a module, the module’s name is
available in the global variable __name__.
128
3/28/23 Programming
Modules Example
fib.py - C:\
129
3/28/23 Programming
Modules Example
131
3/28/23 Programming
Importing ALL Functions
• To import all functions from a module, in the current
symbol table
135
3/28/23 Programming
A sound Package
https://docs.python.org/3/tutorial/modules.html
136
3/28/23 Programming
A sound Package
https://docs.python.org/3/tutorial/modules.html
137
3/28/23xs Programming
__init.py__
• The __init__.py files are required to make
Python treat directories containing the file as
packages.
• This prevents directories with a common name, such
as string, unintentionally hiding valid modules
that occur later on the module search path.
• __init__.py can just be an empty file
• It can also execute initialization code for the package
138
3/28/23 Programming
Importing Modules from Packages
https://docs.python.org/3/tutorial/
modules.html 139
3/28/23 Programming
Importing Modules from Packages
import sound.effects.echo
sound.effects.echo.echofilter(
input, output,
delay=0.7, atten=4
)
140
3/28/23 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
)
141
3/28/23 Programming
Importing Modules from Packages
from sound.effects.echo import echofilter
echofilter(input, output,
delay=0.7, atten=4)
142
3/28/23 Programming
Popular Packages
• pandas, numpy, scipy, matplotlib, …
• Provide a lot of useful functions
143
3/28/23 Programming