SlideShare a Scribd company logo
Python
Software Engineering
Muním Zabidi
Faculty of Electrical Engineering, UTM
Programming Languages
© Muním Zabidi 2
Computer Evolution
Subject 1G 2G 3G 4G 5G
Period 1940-1955 1956-1963 1964-1971 1972-now now-beyond
Circuitry
Vacuum
Transistors
Integrated
VLSI
Many-core,
tubes circuits quantum
Memory 20 KB 128 KB MB GB TB
Speed ms µs MIPS FLOPS TOPS
Programming 1GL 2GL 3GL 4GL 5GL
Example UNIVAC, IBM 1401, IBM 360, 80x86, Google TPU,
computer EDVAC, CDC 3600 UNIVAC 1108 RISC Bristlecone
© Muním Zabidi 3
Language Generations 1GL, 2GL
1GL: Machine Language
Used on 1G computers
In the form of binary numbers
2GL: Assembly Language
Text-based representation of machine language
Code is run thru an assembler into machine language
3GL: High-Level Languages (HLL)
Translated by compilers to get machine language
Code is portable
© Muním Zabidi 4
Language Generations 3GL, 4GL
4GL
term 4GL is actually very imprecise
“4GL” is used for marketing reasons to describe many modern application development tools
typically used to meet special needs of data processing for use by non-expert programmers
For applications as databases, spreadsheets, and program generators
4GLs are essentially non-procedural, whereas 3GLs tend to be procedural, but there is no standard
definition!
5GL
designed to make the computer solve a given problem without the programmer
the user only needs to worry about what problems need to be solved and what conditions need to
be met, without worrying about how to implement a routine or algorithm to solve them
used mainly in artificial intelligence research
© Muním Zabidi 5
Programming Paradigms
imperative declarative
procedural object-oriented logic functional
Programming languages
e.g. FORTRAN, C e.g. C++, Java e.g. Prolog e.g. Haskell, Erlang
© Muním Zabidi 6
Compilers vs Interpreters
Compiler Interpreter
Input Takes entire program as input Takes a single instruction as input
Output Generates executable code Executable code is not generated
What’s Needed
to Run
Just the executable code Source code + interpreter
Speed Once compiled runs quickly but com-
piling can take a long time
Runs more slowly as the source code
is translated every time code is run
Errors Displays all errors during compilation Displays error as it is found during ex-
ecution
Debugging Harder Easier
© Muním Zabidi 7
Language Evolution
© Muním Zabidi 8
Procedure-Oriented Programming
Main design concern is ordering of procedures/functions
Data is mostly global
Data does not belong to any function
© Muním Zabidi 9
Object-Oriented Programming (OOP)
Main design concern is design of classes
Data (attributes) is mostly local
Data belongs to class, encapsulated
© Muním Zabidi 10
Advantages of OOP
Modularity: Something has gone wrong, and you have to find the source of the problem.
When working with object-oriented programming languages, you know exactly where to
look. Objects are self-contained, and an object does its own thing while leaving the other
objects alone.
Ease of development: After programs reach a certain size, OOP are easier than non-OOP.
Being modular, a team can work on multiple objects simultaneously while minimizing
the chance that one person might duplicate someone else’s functionality.
Ease in maintenance: Object-oriented software is easier to understand, therefore easier
to test, debug, and maintain.
Code reuse: Objects can be easily reused for other programs.
Higher software quality: OOP forces developers to deal with high-level concepts and
abstractions.
© Muním Zabidi 11
Running Python
© Muním Zabidi 12
Python Popularity TIOBE Nov 2022
Rank Language Application Share
1 Python 29.48%
2 Java 17.18%
3 Javascript 9.14%
4 C# 6.94%
5 PHP 6.94%
6 C/C++ 6.49%
7 R 3.59%
8 TypeScript 2.18%
9 Swift 2.10%
10 Objective-C 2.06%
https://www.tiobe.com/tiobe-index/
© Muním Zabidi 13
https://levelup.gitconnected.com/if-i-could-only-learn-6-programming-languages-in-my-life-id-learn-these-22e05072dcf3
Running Python Interpreter
The quickest way to write Python code is using the interpreter. Type your Python
instruction, and get your answer the moment you hit the Enter key.
The prompt is changed to >>>
$ python
Python 3.7.6 (default, Jan 8 2020, 13:42:34)
[GCC 7.3.0] :: Anaconda custom (64-bit) on linux
Type "help", "copyright", "credits" or "license" for more information.
>>>
For example:
>>> 42
42
>>> 4 + 2
6
© Muním Zabidi 15
Running Python Scripts
For long programs, it’s better to write Python script files with .py extension. Type the
following in your text editor. Save it as hello.py.
print("Hello, world!")
Run this program by calling
$ python hello.py
Hello, world!
© Muním Zabidi 16
Python Scripts with Shebang
Another way to run Python code is by making the .py scripts executable
Add a shebang line to the top of the script:
#!/usr/bin/python
print("Hello, world!")
Use chmod to make the file executable in Linux.
$ chmod +x hello.py
Running the Python script after making it executable:
$ ./hello.py
Hello, world!
© Muním Zabidi 17
Python Zero to Hero
https://twitter.com/Saboo_Shubham_/status/1587117220785684481/photo/1
Basic Python
© Muním Zabidi 19
Numbers
You can use Python as an interactive calculator
Results can be integer or floating-point, whichever simpler
>>> 7 + 2
9
>>> 7 * 2
14
>>> 1 / 3
0.3333333333333333
>>> 7 ** 2
49
>>> 2 ** .5
1.4142135623730951
>>> 7 % 2
1
Math follows the PEMDAS rule
>>> 2 + 3 * 4
14
>>> 8 / 2 * (2 + 2)
16.0
© Muním Zabidi 20
Variables
Variables are easy to use and reuse
>>> one = 1
>>> one * 2
2
>>> one = ’hello’
>>> one
’hello’
Multiple assignments are amazing
>>> a, b = 1, 2
>>> a, b
(1, 2)
>>> a + b
3
>>> a, b = b, a
>>> a, b
(2, 1)
© Muním Zabidi 21
Boolean
Booleans are useful
>>> boolvar = True
>>> boolvar
True
>>> 2 < 3
True
>>> boolvar = 2 > 3
>>> boolvar
False
>>> x = 5
>>> 2 < x < 10
True
© Muním Zabidi 22
Data Types
Integers are used as much as possible. Floating-point only when necessary.
>>> 22/7
3
>>> 22/7.
3.142857142857143
>>> 355./113
3.1415929203539825
>>> import math
>>> math.pi
3.141592653589793
By the way, approximating π by 355/113 is accurate to 7 digits, the maximum accuracy of
single-precision IEEE 754 numbers.
© Muním Zabidi 23
Strings
Strings are enclosed in single- or double-quotes
No difference between single quotes and double quotes, they can used interchangeably
>>> x = "hello"
>>> y = ’world’
>>> print(x + " " + y)
hello world
Multi-line strings can be written using three single quotes or three double quotes.
>>> x = ’’’This is a multi-line string
... written in
... three lines.’’’
>>> x
’This is a multi-line stringnwritten innthree lines.’
>>> print(x)
This is a multi-line string
written in
three lines.
© Muním Zabidi 24
Flow Control
© Muním Zabidi 25
Conditional Expressions
Result of comparison are Boolean values.
>>> 2 < 3
True
>>> 2 > 3
False
Fancy combinations are possible
>>> x = 5
>>> 2 < x < 10
True
>>> 2 < 3 < 4 < 5 < 6
True
>>> (2 < 3) and (4 > 5)
False
String comparisons:
>>> "python" < "java"
False
Conditional expressions
== equal to
!= not equal to
< less than
> greater than
<= less than or equal to
>= greater than or equal to
Logical expressions
a and b True only if both a and b are True
a or b True if either a or b is True
not a True only if a is False
© Muním Zabidi 26
Branching
The if statement is used to execute a
piece of code only when a boolean
expression is true.
>>> x = 42
>>> if x % 2 == 0: print(’even’)
even
Indent to increase readibility. Or the else
clause is used.
>>> if x%2:
... print("even")
... else:
... print("odd")
...
odd
Use elif where more conditions need to
be checked.
>>> x = 42
>>> if x < 10:
... print(’one digit number’)
... elif x < 100:
... print(’two digit number’)
... else:
... print(’big number’)
...
two digit number
© Muním Zabidi 27
Looping
The while keyword loops when Bolean
test is true.
>>> num = 1
>>> while num <= 5:
... print(num)
... num += 1
...
1
2
3
4
5
for loop is more compact
>>> for i in range(1, 6):
... print(i)
...
1
2
3
4
5
>>> for i in range(5):
... print(i, end=" ")
...
0 1 2 3 4 >>>
© Muním Zabidi 28
Functions
© Muním Zabidi 29
Basics of Functions
Functions are easy in Python.
>>> def sqr(x):
... return x * x
...
>>> sqr(5)
25
>>> sqr(sqr(3))
81
Interesting: In Python, functions can be
passed as arguments to other functions
>>> f = sqr
>>> f(4)
16
>>> def fxy(f, x, y):
... return f(x) + f(y)
...
>>> fxy(sqr, 2, 3)
13
© Muním Zabidi 30
Scope of Variables
Local variables: variables assigned in a
function, and arguments to the function.
Global variables: variables defined in the
top-level.
>>> x,y
(0, 0)
>>> def incr(x):
... y = x+1
... print(x,y)
...
>>> incr(5)
5 6
>>> print(x,y)
0 0
Variables x and y used in function incr are
different than x and y used outside
When Python sees a variable not defined
locally, it tries to find a global variable
with that name.
>>> pi = 355/113
>>> def area(r):
... return pi * r * r
...
>>> area(2)
12.56637168141593
© Muním Zabidi 31
Keyword Arguments
Keyword argument: a name is provided to
the variable as you pass it into the
function.
>>> def diff(x, y):
... return x - y
...
>>> diff(5, 2)
3
>>> diff(x=5, y=2)
3
>>> diff(5, y=2)
3
>>> diff(y=2, x=5)
3
Arguments can have default values.
>>> def increment(x, amount=1):
... return x + amount
...
>>> increment(10)
11
>>> increment(10, 5)
15
>>> increment(10, amount=2)
12
© Muním Zabidi 32
Built-In Functions
Python provides some useful built-in
functions.
>>> min(2, 3)
2
>>> max(3, 4)
4
>>> abs(-3)
3
len computes the length of a string.
>>> len("helloworld")
10
int converts string to integer
str converts integers and other types of
objects to strings.
bin converts integers to binary string
prefixed with 0b
>>> int("50")
50
>>> str(123)
"123"
>>> for i in range(5):
... print(str(i)+’ ’, end=’’)
...
0 1 2 3 4
>>> bin(3)
’0b11’
© Muním Zabidi 33
Built-In Functions Reference
abs() delattr() hash() memoryview() set()
all() dict() help() min() setattr()
any() dir() hex() next() slice()
ascii() divmod() id() object() sorted()
bin() enumerate() input() oct() staticmethod()
bool() eval() int() open() str()
breakpoint() exec() isinstance() ord() sum()
bytearray() filter() issubclass() pow() super()
bytes() float() iter() print() tuple()
callable() format() len() property() type()
chr() frozenset() list() range() vars()
classmethod() getattr() locals() repr() zip()
compile() globals() map() reversed() __import__()
complex() hasattr() max() round()
https://docs.python.org/3/library/functions.html
© Muním Zabidi 34
Methods
Methods functions that work on an
object.
upper is a method available on string
objects.
>>> x = "hello"
>>> x.upper()
’HELLO’
Methods can be assigned to other
variables and can be called separately.
>>> x = ’hello’
>>> f = x.upper
>>> f()
’HELLO’
© Muním Zabidi 35
What are Python Modules?
A Python module is just a python file with
a .py extension.
It can contain variables or functions –
elements that can be referred from
another python file using an import.
Modules can be either:
User-defined
Built-in
© Muním Zabidi 36
User-Defined Modules
Create a module
To create a module, create a Python file
with a .py extension.
Call a module
Modules created with a .py extension can
be used in another Python source file,
using the import statement.
#myModule.py
def myFunction( parameter ):
#define a function in myModule.py
print ( "Course : ", parameter )
To call this Python module myModule.py,
create another Python file callModule.py file
and use the import statement.
import myModule.py:
myModule.myFunction("SKEL4213")
When executed:
Course : SKEL4213
© Muním Zabidi 37
Python Packages
A Python package is just a collection of Python files (or modules)
https://ajaytech.co/2020/04/21/modules-vs-packages-vs-libraries-vs-frameworks/
Built-In Packages
Python ships with a standard package for
common tasks, e.g. time, math, sys
The time package manipulates system
time
>>> import time
>>> time.asctime()
’Mon Nov 2 19:59:14 2020’
The math package has many
mathematical functions and constants
>>> import math
>>> math.pi
3.141592653589793
The dir() built-in function returns a sorted
list of strings containing the names
defined by a module
>>> import math
>>> dir(math)
[’__doc__’, ’__file__’, ’__loader__’,
’__name__’,’__package__’, ’__spec__’,
’acos’, ’acosh’, ’asin’, ’asinh’,
’atan’, ’atan2’, ’atanh’, ’ceil’,
’copysign’, ’cos’, ’cosh’, ’degrees’,
’e’, ’erf’, ’erfc’, ’exp’, ’expm1’,
’fabs’, ’factorial’, ’floor’, ’fmod’,
’frexp’, ’fsum’, ’gamma’, ’gcd’,
’hypot’, ’inf’, ’isclose’, ’isfinite’,
’isinf’, ’isnan’, ’ldexp’,’lgamma’,
’log’, ’log10’, ’log1p’, ’log2’,
’modf’,’nan’, ’pi’, ’pow’, ’radians’,
’remainder’, ’sin’, ’sinh’, ’sqrt’,
’tan’, ’tanh’, ’tau’, ’trunc’]
© Muním Zabidi 39
The sys Package
The sys package manipulates the operating system
$ echo -e "import sysnprint(sys.argv[1])" > try.py
$ cat try.py
import sys
print(sys.argv[1])
$ python try.py hello
hello
$ python try.py hello world
hello
$ python try.py
Traceback (most recent call last):
File "try.py", line 2, in <module>
print(sys.argv[1])
IndexError: list index out of range
We get error because argv[1] was not found.
© Muním Zabidi 40
Python Libraries & Frameworks
A Python library is a collection of Python
modules or packages.
The Python standard library is an example
of a Python package
A framework is a library that has a
particular style to solve a problem
For example, Django and Flask are both
web development frameworks with
differing implementation styles
© Muním Zabidi 41
Collections
© Muním Zabidi 42
Overview
Collections or containers are any object that holds an arbitrary number of other objects.
Containers provide a way to access the contained objects and to iterate over them.
Python has four collection data types:
List is mutable, ordered and indexed. Allows duplicate members.
Tuple is immutable, ordered and indexed. Allows duplicate members.
Set is unordered and unindexed. No duplicate members.
Dictionary is mutable, unordered and indexed. No duplicate members.
mutable = changeable
© Muním Zabidi 43
Lists
A list is a collection that is ordered and changeable.
Lists are written with square brackets.
Lists can implement arrays found in “lower-level” languages
>>> x = [1, 2, 3]
>>> x
[1, 2, 3]
>>> fruits = ["durian", "mango", "banana"]
>>> fruits
[’durian’, ’mango’, ’banana’]
Lists can be heterogeneous
>>> y = [1, 2, "hello", "world", ["another", "list"]]
>>> y
[1, 2, ’hello’, ’world’, [’another’, ’list’]]
The built-in function len can be used on lists.
>>> x = [1, 2, 3]
>>> len(x)
3
© Muním Zabidi 44
Accessing Items in Lists
The [] operator is used to access individual elements of a list.
The first element is indexed with 0, second with 1 and so on.
>>> fruits = ["durian", "mango", "banana"]
>>> fruits[1]
’mango’
>>> fruits[-1]
’banana’
>>> fruits[1]=’papaya’
>>> fruits
[’durian’, ’papaya’, ’banana’]
The for loop can iterate over a list efficiently
>>> fruits = ["durian", "mango", "banana"]
>>> for fruit in fruits:
... print(fruit)
...
durian
mango
banana
© Muním Zabidi 45
Modifying Lists
We can add an element to the list and sort the list.
>>> fruits = [’durian’, ’papaya’, ’banana’]
>>> fruits.append(’kiwi’)
>>> fruits
[’durian’, ’papaya’, ’banana’, ’kiwi’]
>>> fruits.sort()
>>> fruits
[’banana’, ’durian’, ’kiwi’, ’papaya’]
We can remove an element from a list.
>>> fruits = [’durian’, ’papaya’, ’banana’]
>>> fruits.remove(’durian’)
>>> fruits
[’papaya’, ’banana’]
© Muním Zabidi 46
https://www.analyticsvidhya.com/blog/2021/06/
15-functions-you-should-know-to-master-lists-in-python/
https://twitter.com/NikkiSiapno/status/1571775409833889792/photo/1
Tuples
A tuple is a collection that is ordered and unchangeable.
Tuples are written with round brackets (a.k.a. parentheses).
>>> fruits = (’durian’, ’papaya’, ’banana’)
>>> fruits
(’durian’, ’papaya’, ’banana’)
You can even write tuples without the round brackets.
Tuple items are accessed by referring to the index number, inside square brackets:
>>> fruits = ’durian’, ’papaya’, ’banana’
>>> fruits[1]
’papaya’
You can specify a range of indexes by specifying where to start and where to end the
range.
When specifying a range, the return value will be a new tuple with the specified items.
>>> fruits = (’durian’, ’papaya’, ’banana’, ’mango’, ’kiwi’, ’guava’)
>>> fruits[3:5]
(’mango’, ’kiwi’)
© Muním Zabidi 48
Modifyting Tuples
Once a tuple is created, you cannot change its values.
Workaround: convert the tuple into a list, change the list, and convert the list back into a
tuple
>>> x = (’durian’, ’papaya’, ’banana’)
>>> y = list(x)
>>> y[1] = ’kiwi’
>>> x = tuple(y)
>>> x
(’durian’, ’kiwi’, ’banana’)
To determine if a specified item is present in a tuple use the in keyword:
>>> fruits = (’durian’, ’papaya’, ’banana’)
>>> if "banana" in fruits:
... print("Banana is in this tuple")
...
Banana is in this tuple
© Muním Zabidi 49
Sets
A set is a collection that is unordered and unindexed.
Sets are written with curly brackets.
>>> fruits = {’durian’, ’papaya’, ’banana’}
>>> fruits
set([’papaya’, ’banana’, ’durian’])
The order of elements could be different than originally entered.
Indexing does not work because the set is unordered.
>>> fruits[0]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: ’set’ object does not support indexing
© Muním Zabidi 50
Manipulating Sets 1/2
Once a set is created, you cannot change its items, but you can add items.
Use add() to add 1 item
Use update() to add more than 1 item.
>>> fruits = {’durian’, ’papaya’, ’banana’}
>>> fruits.add(’kiwi’)
>>> fruits
set([’kiwi’, ’papaya’, ’banana’, ’durian’])
>>> fruits.update(["mango", "guava"])
>>> fruits
set([’kiwi’, ’papaya’, ’durian’, ’mango’, ’guava’, ’banana’])
© Muním Zabidi 51
Manipulating Sets 2/2
You remove an item using remove() or discard().
You can also use the pop() method to remove the first item. Because sets are unordered,
you will not know what item that gets popped.
>>> fruits = {’durian’, ’papaya’, ’banana’, ’mango’, ’guava’, ’kiwi’}
>>> fruits
set([’kiwi’, ’papaya’, ’banana’, ’mango’, ’guava’, ’durian’])
>>> fruits.discard(’papaya’)
>>> fruits
set([’kiwi’, ’banana’, ’mango’, ’guava’, ’durian’])
>>> fruits.remove(’durian’)
>>> fruits
set([’kiwi’, ’banana’, ’mango’, ’guava’])
>>> fruits.pop()
’kiwi’
>>> fruits
set([’banana’, ’mango’, ’guava’])
© Muním Zabidi 52
Dictionaries
A dictionary is a collection that is unordered, changeable and indexed.
It is also called the hash data structure.
Dictionaries are written with curly brackets, and they have keys and values. The key is
the index pointing to the value.
>>> bike = {
... "brand": "Suzuki",
... "model": "Hayabusa",
... "year" : 1999
... }
>>>
>>>
>>> bike
{’brand’: ’Suzuki’, ’model’: ’Hayabusa’, ’year’: 1999}
The items of a dictionary is accessing using its key name, inside square brackets:
>>> bike[’model’]
’Hayabusa’
© Muním Zabidi 53
Manipulating Dictionaries
You can change the value of a specific item by referring to its key name:
>>> bike[’year’] = 2000
>>> bike
{’brand’: ’Suzuki’, ’model’: ’Hayabusa’, ’year’: 2000}
Adding an item to the dictionary is done by using a new index key and assigning a value
to it:
>>> bike[’color’] = "red"
>>> bike
{’color’: ’red’, ’brand’: ’Suzuki’, ’model’: ’Hayabusa’, ’year’: 2000}
The del keyword removes the item with the specified key name:
>>> bike = { "brand": "Suzuki", "model": "Hayabusa", "year" : 1999 }
>>> del bike[’model’]
>>> bike
{’brand’: ’Suzuki’, ’year’: 1999}
© Muním Zabidi 54
pop and popitem
The pop() method removes the item with the specified key name.
The popped value can be saved.
>>> bike = { "brand": "Suzuki", "model": "Hayabusa", "year" : 1999 }
>>> bike.pop("model")
’Hayabusa’
>>> make = bike.pop(’brand’)
>>> make
’Suzuki’
>>> bike
{’year’: 1999}
The popitem() method removes the last inserted item
In versions before 3.7, a random item is removed instead
>>> bike = { "brand": "Suzuki", "model": "Hayabusa", "year" : 1999 }
>>> bike.popitem()
(’year’, 1999)
>>> bike
{’brand’: ’Suzuki’, ’model’: ’Hayabusa’}
© Muním Zabidi 55
Iterating Through Collections List/Tuple/Set Using Loops
You can loop through a list, tuple or set by using a for loop.
>>> mammals = [ ’elephant’, ’monkey’, ’bat’, ’tiger’, ’tapir’ ]
>>> for animal in mammals:
... print(animal)
...
elephant
monkey
bat
tiger
tapir
© Muním Zabidi 56
Iterating Through Dictionaries
Iterating through a dictionary using for loops is more interesting.
>>> bike = {
... "brand":"Suzuki",
... "model":"Hayabusa",
... "year":1999
... }
>>> # Print all keys
>>> for x in bike:
... print(x)
...
brand
model
year
>>> # Print all values
>>> for x in bike:
... print(bike[x])
...
Suzuki
Hayabusa
1999
>>> # Print all key:value pairs
>>> for x in bike:
... print("%s:%s" %(x, bike[x]))
...
brand:Suzuki
model:Hayabusa
year:1999
© Muním Zabidi 57
Iterating Methods
The keys(), values and items() iterator methods returns a list of keys, values and (key,
value) pairs, respectively.
>>> bike = { "brand": "Suzuki", "model": "Hayabusa", "year" : 1999 }
>>> bike.keys()
dict_keys([’brand’, ’model’, ’year’])
>>> bike.values()
dict_values([’Suzuki’, ’Hayabusa’, 1999])
>>> bike.items()
dict_items([(’brand’, ’Suzuki’), (’model’, ’Hayabusa’), (’year’, 1999)])
>>> for x,y in bike.items():
... print(x,y)
...
brand Suzuki
model Hayabusa
year 1999
© Muním Zabidi 58
Exceptions
© Muním Zabidi 59
Syntax Errors
>>> print (1/)
File "<stdin>", line 1
print (1/)
^
SyntaxError: invalid syntax
The parser repeats the offending line and arrows indicate where the syntax error was
detected. Make the correction below and run your code again:
>>> print (1/0)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ZeroDivisionError: division by zero
This time, you’ll get an exception.
© Muním Zabidi 60
Exception Examples
TypeError exception:
>>> 2 + "2"
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for +: ’int’ and ’str’
NameError exception:
>>> 2 + 2*x
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name ’x’ is not defined
© Muním Zabidi 61
Basic Exception Handling
try, except, else, and finally keywords are used.
>>> try:
... print(foo)
... except:
... print("An exception has occurred")
...
An exception has occurred
© Muním Zabidi 62
Multiple Exceptions
One block, one error type:
try:
print(1/0)
except ZeroDivisionError:
print("You cannot divide a value with zero"")
except:
print("Something else went wrong")
© Muním Zabidi 63
Multiple Exceptions
If no errors at all, run else block:
try:
print("Hello")
except:
print("Something went wrong")
else:
print("Nothing went wrong")
© Muním Zabidi 64
Multiple Exceptions
finally block executed regardless of error status:
try:
print("Hello")
except:
print("Something went wrong")
finally:
print("The ’try except’ is finished")
© Muním Zabidi 65
Practical Example
Save this file as trywrite.py
path = ’data.txt’
try:
fp = open(path)
try:
fp.write(’Zam zam alakazam’)
except:
print("Unable to write.")
finally:
fp.close()
except:
print(f"File {path} is not found!")
Run:
% python3 trywrite.py
File data.txt is not found!
Create a blank file called data.txt at the
Linux prompt and rerun the script.
% touch data.txt
% python3 trywrite.py
Unable to write.
© Muním Zabidi 66
https://education.launchcode.org/lchs/chapters/introduction/why-learn-python.html

More Related Content

Similar to Python Software Engineering Python Software Engineering (20)

C463_02_python.ppt
C463_02_python.pptC463_02_python.ppt
C463_02_python.ppt
DiegoARosales
 
C463_02_python.ppt
C463_02_python.pptC463_02_python.ppt
C463_02_python.ppt
athulprathap1
 
Introduction To Programming with Python
Introduction To Programming with PythonIntroduction To Programming with Python
Introduction To Programming with Python
Sushant Mane
 
Python PPT by Sushil Sir.pptx
Python PPT by Sushil Sir.pptxPython PPT by Sushil Sir.pptx
Python PPT by Sushil Sir.pptx
sushil155005
 
First Steps in Python Programming
First Steps in Python ProgrammingFirst Steps in Python Programming
First Steps in Python Programming
Dozie Agbo
 
python introduction initial lecture unit1.pptx
python introduction initial lecture unit1.pptxpython introduction initial lecture unit1.pptx
python introduction initial lecture unit1.pptx
ChandraPrakash715640
 
Introduction to python
Introduction to pythonIntroduction to python
Introduction to python
Mohammed Rafi
 
Python introduction towards data science
Python introduction towards data sciencePython introduction towards data science
Python introduction towards data science
deepak teja
 
Python tutorialfeb152012
Python tutorialfeb152012Python tutorialfeb152012
Python tutorialfeb152012
Shani729
 
An Intro to Python in 30 minutes
An Intro to Python in 30 minutesAn Intro to Python in 30 minutes
An Intro to Python in 30 minutes
Sumit Raj
 
Introduction to Python Programming
Introduction to Python ProgrammingIntroduction to Python Programming
Introduction to Python Programming
VijaySharma802
 
C463_02_python.ppt,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,
C463_02_python.ppt,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,C463_02_python.ppt,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,
C463_02_python.ppt,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,
divijareddy0502
 
C463_02intoduction_to_python_to learnGAI.ppt
C463_02intoduction_to_python_to learnGAI.pptC463_02intoduction_to_python_to learnGAI.ppt
C463_02intoduction_to_python_to learnGAI.ppt
AhmedHamzaJandoubi
 
Python Seminar PPT
Python Seminar PPTPython Seminar PPT
Python Seminar PPT
Shivam Gupta
 
Python
PythonPython
Python
Shivam Gupta
 
python presntation 2.pptx
python presntation 2.pptxpython presntation 2.pptx
python presntation 2.pptx
Arpittripathi45
 
python-160403194316.pdf
python-160403194316.pdfpython-160403194316.pdf
python-160403194316.pdf
gmadhu8
 
Introduction to python & its applications.ppt
Introduction to python & its applications.pptIntroduction to python & its applications.ppt
Introduction to python & its applications.ppt
PradeepNB2
 
Introduction to Python Programming .pptx
Introduction to  Python Programming .pptxIntroduction to  Python Programming .pptx
Introduction to Python Programming .pptx
NaynaSagarDahatonde
 
Programming Under Linux In Python
Programming Under Linux In PythonProgramming Under Linux In Python
Programming Under Linux In Python
Marwan Osman
 
Introduction To Programming with Python
Introduction To Programming with PythonIntroduction To Programming with Python
Introduction To Programming with Python
Sushant Mane
 
Python PPT by Sushil Sir.pptx
Python PPT by Sushil Sir.pptxPython PPT by Sushil Sir.pptx
Python PPT by Sushil Sir.pptx
sushil155005
 
First Steps in Python Programming
First Steps in Python ProgrammingFirst Steps in Python Programming
First Steps in Python Programming
Dozie Agbo
 
python introduction initial lecture unit1.pptx
python introduction initial lecture unit1.pptxpython introduction initial lecture unit1.pptx
python introduction initial lecture unit1.pptx
ChandraPrakash715640
 
Introduction to python
Introduction to pythonIntroduction to python
Introduction to python
Mohammed Rafi
 
Python introduction towards data science
Python introduction towards data sciencePython introduction towards data science
Python introduction towards data science
deepak teja
 
Python tutorialfeb152012
Python tutorialfeb152012Python tutorialfeb152012
Python tutorialfeb152012
Shani729
 
An Intro to Python in 30 minutes
An Intro to Python in 30 minutesAn Intro to Python in 30 minutes
An Intro to Python in 30 minutes
Sumit Raj
 
Introduction to Python Programming
Introduction to Python ProgrammingIntroduction to Python Programming
Introduction to Python Programming
VijaySharma802
 
C463_02_python.ppt,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,
C463_02_python.ppt,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,C463_02_python.ppt,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,
C463_02_python.ppt,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,
divijareddy0502
 
C463_02intoduction_to_python_to learnGAI.ppt
C463_02intoduction_to_python_to learnGAI.pptC463_02intoduction_to_python_to learnGAI.ppt
C463_02intoduction_to_python_to learnGAI.ppt
AhmedHamzaJandoubi
 
Python Seminar PPT
Python Seminar PPTPython Seminar PPT
Python Seminar PPT
Shivam Gupta
 
python presntation 2.pptx
python presntation 2.pptxpython presntation 2.pptx
python presntation 2.pptx
Arpittripathi45
 
python-160403194316.pdf
python-160403194316.pdfpython-160403194316.pdf
python-160403194316.pdf
gmadhu8
 
Introduction to python & its applications.ppt
Introduction to python & its applications.pptIntroduction to python & its applications.ppt
Introduction to python & its applications.ppt
PradeepNB2
 
Introduction to Python Programming .pptx
Introduction to  Python Programming .pptxIntroduction to  Python Programming .pptx
Introduction to Python Programming .pptx
NaynaSagarDahatonde
 
Programming Under Linux In Python
Programming Under Linux In PythonProgramming Under Linux In Python
Programming Under Linux In Python
Marwan Osman
 

Recently uploaded (20)

社内勉強会資料_Chain of Thought .
社内勉強会資料_Chain of Thought                           .社内勉強会資料_Chain of Thought                           .
社内勉強会資料_Chain of Thought .
NABLAS株式会社
 
New Microsoft Office Word Documentfrf.docx
New Microsoft Office Word Documentfrf.docxNew Microsoft Office Word Documentfrf.docx
New Microsoft Office Word Documentfrf.docx
misheetasah
 
Development of Portable Biomass Briquetting Machine (S, A & D)-1.pptx
Development of Portable Biomass Briquetting Machine (S, A & D)-1.pptxDevelopment of Portable Biomass Briquetting Machine (S, A & D)-1.pptx
Development of Portable Biomass Briquetting Machine (S, A & D)-1.pptx
aniket862935
 
SEW make Brake BE05 – BE30 Brake – Repair Kit
SEW make Brake BE05 – BE30 Brake – Repair KitSEW make Brake BE05 – BE30 Brake – Repair Kit
SEW make Brake BE05 – BE30 Brake – Repair Kit
projectultramechanix
 
Third Review PPT that consists of the project d etails like abstract.
Third Review PPT that consists of the project d etails like abstract.Third Review PPT that consists of the project d etails like abstract.
Third Review PPT that consists of the project d etails like abstract.
Sowndarya6
 
IOt Based Research on Challenges and Future
IOt Based Research on Challenges and FutureIOt Based Research on Challenges and Future
IOt Based Research on Challenges and Future
SACHINSAHU821405
 
362 Alec Data Center Solutions-Slysium Data Center-AUH-ABB Furse.pdf
362 Alec Data Center Solutions-Slysium Data Center-AUH-ABB Furse.pdf362 Alec Data Center Solutions-Slysium Data Center-AUH-ABB Furse.pdf
362 Alec Data Center Solutions-Slysium Data Center-AUH-ABB Furse.pdf
djiceramil
 
operationg systemsdocumentmemorymanagement
operationg systemsdocumentmemorymanagementoperationg systemsdocumentmemorymanagement
operationg systemsdocumentmemorymanagement
SNIGDHAAPPANABHOTLA
 
Research_Sensitization_&_Innovative_Project_Development.pptx
Research_Sensitization_&_Innovative_Project_Development.pptxResearch_Sensitization_&_Innovative_Project_Development.pptx
Research_Sensitization_&_Innovative_Project_Development.pptx
niranjancse
 
IntroSlides-June-GDG-Cloud-Munich community [email protected]
IntroSlides-June-GDG-Cloud-Munich community gathering@Netlight.pdfIntroSlides-June-GDG-Cloud-Munich community gathering@Netlight.pdf
IntroSlides-June-GDG-Cloud-Munich community [email protected]
Luiz Carneiro
 
362 Alec Data Center Solutions-Slysium Data Center-AUH-ABB Furse.pdf
362 Alec Data Center Solutions-Slysium Data Center-AUH-ABB Furse.pdf362 Alec Data Center Solutions-Slysium Data Center-AUH-ABB Furse.pdf
362 Alec Data Center Solutions-Slysium Data Center-AUH-ABB Furse.pdf
djiceramil
 
ACEP Magazine Fifth Edition on 5june2025
ACEP Magazine Fifth Edition on 5june2025ACEP Magazine Fifth Edition on 5june2025
ACEP Magazine Fifth Edition on 5june2025
Rahul
 
Présentation_gestion[1] [Autosaved].pptx
Présentation_gestion[1] [Autosaved].pptxPrésentation_gestion[1] [Autosaved].pptx
Présentation_gestion[1] [Autosaved].pptx
KHADIJAESSAKET
 
Structural Design for Residential-to-Restaurant Conversion
Structural Design for Residential-to-Restaurant ConversionStructural Design for Residential-to-Restaurant Conversion
Structural Design for Residential-to-Restaurant Conversion
DanielRoman285499
 
Rearchitecturing a 9-year-old legacy Laravel application.pdf
Rearchitecturing a 9-year-old legacy Laravel application.pdfRearchitecturing a 9-year-old legacy Laravel application.pdf
Rearchitecturing a 9-year-old legacy Laravel application.pdf
Takumi Amitani
 
May 2025: Top 10 Read Articles Advanced Information Technology
May 2025: Top 10 Read Articles Advanced Information TechnologyMay 2025: Top 10 Read Articles Advanced Information Technology
May 2025: Top 10 Read Articles Advanced Information Technology
ijait
 
Artificial Power 2025 raport krajobrazowy
Artificial Power 2025 raport krajobrazowyArtificial Power 2025 raport krajobrazowy
Artificial Power 2025 raport krajobrazowy
dominikamizerska1
 
Flow Chart Proses Bisnis prosscesss.docx
Flow Chart Proses Bisnis prosscesss.docxFlow Chart Proses Bisnis prosscesss.docx
Flow Chart Proses Bisnis prosscesss.docx
rifka575530
 
Semi-Conductor ppt ShubhamSeSemi-Con.pptx
Semi-Conductor ppt ShubhamSeSemi-Con.pptxSemi-Conductor ppt ShubhamSeSemi-Con.pptx
Semi-Conductor ppt ShubhamSeSemi-Con.pptx
studyshubham18
 
Pavement and its types, Application of rigid and Flexible Pavements
Pavement and its types, Application of rigid and Flexible PavementsPavement and its types, Application of rigid and Flexible Pavements
Pavement and its types, Application of rigid and Flexible Pavements
Sakthivel M
 
社内勉強会資料_Chain of Thought .
社内勉強会資料_Chain of Thought                           .社内勉強会資料_Chain of Thought                           .
社内勉強会資料_Chain of Thought .
NABLAS株式会社
 
New Microsoft Office Word Documentfrf.docx
New Microsoft Office Word Documentfrf.docxNew Microsoft Office Word Documentfrf.docx
New Microsoft Office Word Documentfrf.docx
misheetasah
 
Development of Portable Biomass Briquetting Machine (S, A & D)-1.pptx
Development of Portable Biomass Briquetting Machine (S, A & D)-1.pptxDevelopment of Portable Biomass Briquetting Machine (S, A & D)-1.pptx
Development of Portable Biomass Briquetting Machine (S, A & D)-1.pptx
aniket862935
 
SEW make Brake BE05 – BE30 Brake – Repair Kit
SEW make Brake BE05 – BE30 Brake – Repair KitSEW make Brake BE05 – BE30 Brake – Repair Kit
SEW make Brake BE05 – BE30 Brake – Repair Kit
projectultramechanix
 
Third Review PPT that consists of the project d etails like abstract.
Third Review PPT that consists of the project d etails like abstract.Third Review PPT that consists of the project d etails like abstract.
Third Review PPT that consists of the project d etails like abstract.
Sowndarya6
 
IOt Based Research on Challenges and Future
IOt Based Research on Challenges and FutureIOt Based Research on Challenges and Future
IOt Based Research on Challenges and Future
SACHINSAHU821405
 
362 Alec Data Center Solutions-Slysium Data Center-AUH-ABB Furse.pdf
362 Alec Data Center Solutions-Slysium Data Center-AUH-ABB Furse.pdf362 Alec Data Center Solutions-Slysium Data Center-AUH-ABB Furse.pdf
362 Alec Data Center Solutions-Slysium Data Center-AUH-ABB Furse.pdf
djiceramil
 
operationg systemsdocumentmemorymanagement
operationg systemsdocumentmemorymanagementoperationg systemsdocumentmemorymanagement
operationg systemsdocumentmemorymanagement
SNIGDHAAPPANABHOTLA
 
Research_Sensitization_&_Innovative_Project_Development.pptx
Research_Sensitization_&_Innovative_Project_Development.pptxResearch_Sensitization_&_Innovative_Project_Development.pptx
Research_Sensitization_&_Innovative_Project_Development.pptx
niranjancse
 
362 Alec Data Center Solutions-Slysium Data Center-AUH-ABB Furse.pdf
362 Alec Data Center Solutions-Slysium Data Center-AUH-ABB Furse.pdf362 Alec Data Center Solutions-Slysium Data Center-AUH-ABB Furse.pdf
362 Alec Data Center Solutions-Slysium Data Center-AUH-ABB Furse.pdf
djiceramil
 
ACEP Magazine Fifth Edition on 5june2025
ACEP Magazine Fifth Edition on 5june2025ACEP Magazine Fifth Edition on 5june2025
ACEP Magazine Fifth Edition on 5june2025
Rahul
 
Présentation_gestion[1] [Autosaved].pptx
Présentation_gestion[1] [Autosaved].pptxPrésentation_gestion[1] [Autosaved].pptx
Présentation_gestion[1] [Autosaved].pptx
KHADIJAESSAKET
 
Structural Design for Residential-to-Restaurant Conversion
Structural Design for Residential-to-Restaurant ConversionStructural Design for Residential-to-Restaurant Conversion
Structural Design for Residential-to-Restaurant Conversion
DanielRoman285499
 
Rearchitecturing a 9-year-old legacy Laravel application.pdf
Rearchitecturing a 9-year-old legacy Laravel application.pdfRearchitecturing a 9-year-old legacy Laravel application.pdf
Rearchitecturing a 9-year-old legacy Laravel application.pdf
Takumi Amitani
 
May 2025: Top 10 Read Articles Advanced Information Technology
May 2025: Top 10 Read Articles Advanced Information TechnologyMay 2025: Top 10 Read Articles Advanced Information Technology
May 2025: Top 10 Read Articles Advanced Information Technology
ijait
 
Artificial Power 2025 raport krajobrazowy
Artificial Power 2025 raport krajobrazowyArtificial Power 2025 raport krajobrazowy
Artificial Power 2025 raport krajobrazowy
dominikamizerska1
 
Flow Chart Proses Bisnis prosscesss.docx
Flow Chart Proses Bisnis prosscesss.docxFlow Chart Proses Bisnis prosscesss.docx
Flow Chart Proses Bisnis prosscesss.docx
rifka575530
 
Semi-Conductor ppt ShubhamSeSemi-Con.pptx
Semi-Conductor ppt ShubhamSeSemi-Con.pptxSemi-Conductor ppt ShubhamSeSemi-Con.pptx
Semi-Conductor ppt ShubhamSeSemi-Con.pptx
studyshubham18
 
Pavement and its types, Application of rigid and Flexible Pavements
Pavement and its types, Application of rigid and Flexible PavementsPavement and its types, Application of rigid and Flexible Pavements
Pavement and its types, Application of rigid and Flexible Pavements
Sakthivel M
 
Ad

Python Software Engineering Python Software Engineering

  • 1. Python Software Engineering Muním Zabidi Faculty of Electrical Engineering, UTM
  • 3. Computer Evolution Subject 1G 2G 3G 4G 5G Period 1940-1955 1956-1963 1964-1971 1972-now now-beyond Circuitry Vacuum Transistors Integrated VLSI Many-core, tubes circuits quantum Memory 20 KB 128 KB MB GB TB Speed ms µs MIPS FLOPS TOPS Programming 1GL 2GL 3GL 4GL 5GL Example UNIVAC, IBM 1401, IBM 360, 80x86, Google TPU, computer EDVAC, CDC 3600 UNIVAC 1108 RISC Bristlecone © Muním Zabidi 3
  • 4. Language Generations 1GL, 2GL 1GL: Machine Language Used on 1G computers In the form of binary numbers 2GL: Assembly Language Text-based representation of machine language Code is run thru an assembler into machine language 3GL: High-Level Languages (HLL) Translated by compilers to get machine language Code is portable © Muním Zabidi 4
  • 5. Language Generations 3GL, 4GL 4GL term 4GL is actually very imprecise “4GL” is used for marketing reasons to describe many modern application development tools typically used to meet special needs of data processing for use by non-expert programmers For applications as databases, spreadsheets, and program generators 4GLs are essentially non-procedural, whereas 3GLs tend to be procedural, but there is no standard definition! 5GL designed to make the computer solve a given problem without the programmer the user only needs to worry about what problems need to be solved and what conditions need to be met, without worrying about how to implement a routine or algorithm to solve them used mainly in artificial intelligence research © Muním Zabidi 5
  • 6. Programming Paradigms imperative declarative procedural object-oriented logic functional Programming languages e.g. FORTRAN, C e.g. C++, Java e.g. Prolog e.g. Haskell, Erlang © Muním Zabidi 6
  • 7. Compilers vs Interpreters Compiler Interpreter Input Takes entire program as input Takes a single instruction as input Output Generates executable code Executable code is not generated What’s Needed to Run Just the executable code Source code + interpreter Speed Once compiled runs quickly but com- piling can take a long time Runs more slowly as the source code is translated every time code is run Errors Displays all errors during compilation Displays error as it is found during ex- ecution Debugging Harder Easier © Muním Zabidi 7
  • 9. Procedure-Oriented Programming Main design concern is ordering of procedures/functions Data is mostly global Data does not belong to any function © Muním Zabidi 9
  • 10. Object-Oriented Programming (OOP) Main design concern is design of classes Data (attributes) is mostly local Data belongs to class, encapsulated © Muním Zabidi 10
  • 11. Advantages of OOP Modularity: Something has gone wrong, and you have to find the source of the problem. When working with object-oriented programming languages, you know exactly where to look. Objects are self-contained, and an object does its own thing while leaving the other objects alone. Ease of development: After programs reach a certain size, OOP are easier than non-OOP. Being modular, a team can work on multiple objects simultaneously while minimizing the chance that one person might duplicate someone else’s functionality. Ease in maintenance: Object-oriented software is easier to understand, therefore easier to test, debug, and maintain. Code reuse: Objects can be easily reused for other programs. Higher software quality: OOP forces developers to deal with high-level concepts and abstractions. © Muním Zabidi 11
  • 13. Python Popularity TIOBE Nov 2022 Rank Language Application Share 1 Python 29.48% 2 Java 17.18% 3 Javascript 9.14% 4 C# 6.94% 5 PHP 6.94% 6 C/C++ 6.49% 7 R 3.59% 8 TypeScript 2.18% 9 Swift 2.10% 10 Objective-C 2.06% https://www.tiobe.com/tiobe-index/ © Muním Zabidi 13
  • 15. Running Python Interpreter The quickest way to write Python code is using the interpreter. Type your Python instruction, and get your answer the moment you hit the Enter key. The prompt is changed to >>> $ python Python 3.7.6 (default, Jan 8 2020, 13:42:34) [GCC 7.3.0] :: Anaconda custom (64-bit) on linux Type "help", "copyright", "credits" or "license" for more information. >>> For example: >>> 42 42 >>> 4 + 2 6 © Muním Zabidi 15
  • 16. Running Python Scripts For long programs, it’s better to write Python script files with .py extension. Type the following in your text editor. Save it as hello.py. print("Hello, world!") Run this program by calling $ python hello.py Hello, world! © Muním Zabidi 16
  • 17. Python Scripts with Shebang Another way to run Python code is by making the .py scripts executable Add a shebang line to the top of the script: #!/usr/bin/python print("Hello, world!") Use chmod to make the file executable in Linux. $ chmod +x hello.py Running the Python script after making it executable: $ ./hello.py Hello, world! © Muním Zabidi 17
  • 18. Python Zero to Hero https://twitter.com/Saboo_Shubham_/status/1587117220785684481/photo/1
  • 20. Numbers You can use Python as an interactive calculator Results can be integer or floating-point, whichever simpler >>> 7 + 2 9 >>> 7 * 2 14 >>> 1 / 3 0.3333333333333333 >>> 7 ** 2 49 >>> 2 ** .5 1.4142135623730951 >>> 7 % 2 1 Math follows the PEMDAS rule >>> 2 + 3 * 4 14 >>> 8 / 2 * (2 + 2) 16.0 © Muním Zabidi 20
  • 21. Variables Variables are easy to use and reuse >>> one = 1 >>> one * 2 2 >>> one = ’hello’ >>> one ’hello’ Multiple assignments are amazing >>> a, b = 1, 2 >>> a, b (1, 2) >>> a + b 3 >>> a, b = b, a >>> a, b (2, 1) © Muním Zabidi 21
  • 22. Boolean Booleans are useful >>> boolvar = True >>> boolvar True >>> 2 < 3 True >>> boolvar = 2 > 3 >>> boolvar False >>> x = 5 >>> 2 < x < 10 True © Muním Zabidi 22
  • 23. Data Types Integers are used as much as possible. Floating-point only when necessary. >>> 22/7 3 >>> 22/7. 3.142857142857143 >>> 355./113 3.1415929203539825 >>> import math >>> math.pi 3.141592653589793 By the way, approximating π by 355/113 is accurate to 7 digits, the maximum accuracy of single-precision IEEE 754 numbers. © Muním Zabidi 23
  • 24. Strings Strings are enclosed in single- or double-quotes No difference between single quotes and double quotes, they can used interchangeably >>> x = "hello" >>> y = ’world’ >>> print(x + " " + y) hello world Multi-line strings can be written using three single quotes or three double quotes. >>> x = ’’’This is a multi-line string ... written in ... three lines.’’’ >>> x ’This is a multi-line stringnwritten innthree lines.’ >>> print(x) This is a multi-line string written in three lines. © Muním Zabidi 24
  • 26. Conditional Expressions Result of comparison are Boolean values. >>> 2 < 3 True >>> 2 > 3 False Fancy combinations are possible >>> x = 5 >>> 2 < x < 10 True >>> 2 < 3 < 4 < 5 < 6 True >>> (2 < 3) and (4 > 5) False String comparisons: >>> "python" < "java" False Conditional expressions == equal to != not equal to < less than > greater than <= less than or equal to >= greater than or equal to Logical expressions a and b True only if both a and b are True a or b True if either a or b is True not a True only if a is False © Muním Zabidi 26
  • 27. Branching The if statement is used to execute a piece of code only when a boolean expression is true. >>> x = 42 >>> if x % 2 == 0: print(’even’) even Indent to increase readibility. Or the else clause is used. >>> if x%2: ... print("even") ... else: ... print("odd") ... odd Use elif where more conditions need to be checked. >>> x = 42 >>> if x < 10: ... print(’one digit number’) ... elif x < 100: ... print(’two digit number’) ... else: ... print(’big number’) ... two digit number © Muním Zabidi 27
  • 28. Looping The while keyword loops when Bolean test is true. >>> num = 1 >>> while num <= 5: ... print(num) ... num += 1 ... 1 2 3 4 5 for loop is more compact >>> for i in range(1, 6): ... print(i) ... 1 2 3 4 5 >>> for i in range(5): ... print(i, end=" ") ... 0 1 2 3 4 >>> © Muním Zabidi 28
  • 30. Basics of Functions Functions are easy in Python. >>> def sqr(x): ... return x * x ... >>> sqr(5) 25 >>> sqr(sqr(3)) 81 Interesting: In Python, functions can be passed as arguments to other functions >>> f = sqr >>> f(4) 16 >>> def fxy(f, x, y): ... return f(x) + f(y) ... >>> fxy(sqr, 2, 3) 13 © Muním Zabidi 30
  • 31. Scope of Variables Local variables: variables assigned in a function, and arguments to the function. Global variables: variables defined in the top-level. >>> x,y (0, 0) >>> def incr(x): ... y = x+1 ... print(x,y) ... >>> incr(5) 5 6 >>> print(x,y) 0 0 Variables x and y used in function incr are different than x and y used outside When Python sees a variable not defined locally, it tries to find a global variable with that name. >>> pi = 355/113 >>> def area(r): ... return pi * r * r ... >>> area(2) 12.56637168141593 © Muním Zabidi 31
  • 32. Keyword Arguments Keyword argument: a name is provided to the variable as you pass it into the function. >>> def diff(x, y): ... return x - y ... >>> diff(5, 2) 3 >>> diff(x=5, y=2) 3 >>> diff(5, y=2) 3 >>> diff(y=2, x=5) 3 Arguments can have default values. >>> def increment(x, amount=1): ... return x + amount ... >>> increment(10) 11 >>> increment(10, 5) 15 >>> increment(10, amount=2) 12 © Muním Zabidi 32
  • 33. Built-In Functions Python provides some useful built-in functions. >>> min(2, 3) 2 >>> max(3, 4) 4 >>> abs(-3) 3 len computes the length of a string. >>> len("helloworld") 10 int converts string to integer str converts integers and other types of objects to strings. bin converts integers to binary string prefixed with 0b >>> int("50") 50 >>> str(123) "123" >>> for i in range(5): ... print(str(i)+’ ’, end=’’) ... 0 1 2 3 4 >>> bin(3) ’0b11’ © Muním Zabidi 33
  • 34. Built-In Functions Reference abs() delattr() hash() memoryview() set() all() dict() help() min() setattr() any() dir() hex() next() slice() ascii() divmod() id() object() sorted() bin() enumerate() input() oct() staticmethod() bool() eval() int() open() str() breakpoint() exec() isinstance() ord() sum() bytearray() filter() issubclass() pow() super() bytes() float() iter() print() tuple() callable() format() len() property() type() chr() frozenset() list() range() vars() classmethod() getattr() locals() repr() zip() compile() globals() map() reversed() __import__() complex() hasattr() max() round() https://docs.python.org/3/library/functions.html © Muním Zabidi 34
  • 35. Methods Methods functions that work on an object. upper is a method available on string objects. >>> x = "hello" >>> x.upper() ’HELLO’ Methods can be assigned to other variables and can be called separately. >>> x = ’hello’ >>> f = x.upper >>> f() ’HELLO’ © Muním Zabidi 35
  • 36. What are Python Modules? A Python module is just a python file with a .py extension. It can contain variables or functions – elements that can be referred from another python file using an import. Modules can be either: User-defined Built-in © Muním Zabidi 36
  • 37. User-Defined Modules Create a module To create a module, create a Python file with a .py extension. Call a module Modules created with a .py extension can be used in another Python source file, using the import statement. #myModule.py def myFunction( parameter ): #define a function in myModule.py print ( "Course : ", parameter ) To call this Python module myModule.py, create another Python file callModule.py file and use the import statement. import myModule.py: myModule.myFunction("SKEL4213") When executed: Course : SKEL4213 © Muním Zabidi 37
  • 38. Python Packages A Python package is just a collection of Python files (or modules) https://ajaytech.co/2020/04/21/modules-vs-packages-vs-libraries-vs-frameworks/
  • 39. Built-In Packages Python ships with a standard package for common tasks, e.g. time, math, sys The time package manipulates system time >>> import time >>> time.asctime() ’Mon Nov 2 19:59:14 2020’ The math package has many mathematical functions and constants >>> import math >>> math.pi 3.141592653589793 The dir() built-in function returns a sorted list of strings containing the names defined by a module >>> import math >>> dir(math) [’__doc__’, ’__file__’, ’__loader__’, ’__name__’,’__package__’, ’__spec__’, ’acos’, ’acosh’, ’asin’, ’asinh’, ’atan’, ’atan2’, ’atanh’, ’ceil’, ’copysign’, ’cos’, ’cosh’, ’degrees’, ’e’, ’erf’, ’erfc’, ’exp’, ’expm1’, ’fabs’, ’factorial’, ’floor’, ’fmod’, ’frexp’, ’fsum’, ’gamma’, ’gcd’, ’hypot’, ’inf’, ’isclose’, ’isfinite’, ’isinf’, ’isnan’, ’ldexp’,’lgamma’, ’log’, ’log10’, ’log1p’, ’log2’, ’modf’,’nan’, ’pi’, ’pow’, ’radians’, ’remainder’, ’sin’, ’sinh’, ’sqrt’, ’tan’, ’tanh’, ’tau’, ’trunc’] © Muním Zabidi 39
  • 40. The sys Package The sys package manipulates the operating system $ echo -e "import sysnprint(sys.argv[1])" > try.py $ cat try.py import sys print(sys.argv[1]) $ python try.py hello hello $ python try.py hello world hello $ python try.py Traceback (most recent call last): File "try.py", line 2, in <module> print(sys.argv[1]) IndexError: list index out of range We get error because argv[1] was not found. © Muním Zabidi 40
  • 41. Python Libraries & Frameworks A Python library is a collection of Python modules or packages. The Python standard library is an example of a Python package A framework is a library that has a particular style to solve a problem For example, Django and Flask are both web development frameworks with differing implementation styles © Muním Zabidi 41
  • 43. Overview Collections or containers are any object that holds an arbitrary number of other objects. Containers provide a way to access the contained objects and to iterate over them. Python has four collection data types: List is mutable, ordered and indexed. Allows duplicate members. Tuple is immutable, ordered and indexed. Allows duplicate members. Set is unordered and unindexed. No duplicate members. Dictionary is mutable, unordered and indexed. No duplicate members. mutable = changeable © Muním Zabidi 43
  • 44. Lists A list is a collection that is ordered and changeable. Lists are written with square brackets. Lists can implement arrays found in “lower-level” languages >>> x = [1, 2, 3] >>> x [1, 2, 3] >>> fruits = ["durian", "mango", "banana"] >>> fruits [’durian’, ’mango’, ’banana’] Lists can be heterogeneous >>> y = [1, 2, "hello", "world", ["another", "list"]] >>> y [1, 2, ’hello’, ’world’, [’another’, ’list’]] The built-in function len can be used on lists. >>> x = [1, 2, 3] >>> len(x) 3 © Muním Zabidi 44
  • 45. Accessing Items in Lists The [] operator is used to access individual elements of a list. The first element is indexed with 0, second with 1 and so on. >>> fruits = ["durian", "mango", "banana"] >>> fruits[1] ’mango’ >>> fruits[-1] ’banana’ >>> fruits[1]=’papaya’ >>> fruits [’durian’, ’papaya’, ’banana’] The for loop can iterate over a list efficiently >>> fruits = ["durian", "mango", "banana"] >>> for fruit in fruits: ... print(fruit) ... durian mango banana © Muním Zabidi 45
  • 46. Modifying Lists We can add an element to the list and sort the list. >>> fruits = [’durian’, ’papaya’, ’banana’] >>> fruits.append(’kiwi’) >>> fruits [’durian’, ’papaya’, ’banana’, ’kiwi’] >>> fruits.sort() >>> fruits [’banana’, ’durian’, ’kiwi’, ’papaya’] We can remove an element from a list. >>> fruits = [’durian’, ’papaya’, ’banana’] >>> fruits.remove(’durian’) >>> fruits [’papaya’, ’banana’] © Muním Zabidi 46
  • 48. Tuples A tuple is a collection that is ordered and unchangeable. Tuples are written with round brackets (a.k.a. parentheses). >>> fruits = (’durian’, ’papaya’, ’banana’) >>> fruits (’durian’, ’papaya’, ’banana’) You can even write tuples without the round brackets. Tuple items are accessed by referring to the index number, inside square brackets: >>> fruits = ’durian’, ’papaya’, ’banana’ >>> fruits[1] ’papaya’ You can specify a range of indexes by specifying where to start and where to end the range. When specifying a range, the return value will be a new tuple with the specified items. >>> fruits = (’durian’, ’papaya’, ’banana’, ’mango’, ’kiwi’, ’guava’) >>> fruits[3:5] (’mango’, ’kiwi’) © Muním Zabidi 48
  • 49. Modifyting Tuples Once a tuple is created, you cannot change its values. Workaround: convert the tuple into a list, change the list, and convert the list back into a tuple >>> x = (’durian’, ’papaya’, ’banana’) >>> y = list(x) >>> y[1] = ’kiwi’ >>> x = tuple(y) >>> x (’durian’, ’kiwi’, ’banana’) To determine if a specified item is present in a tuple use the in keyword: >>> fruits = (’durian’, ’papaya’, ’banana’) >>> if "banana" in fruits: ... print("Banana is in this tuple") ... Banana is in this tuple © Muním Zabidi 49
  • 50. Sets A set is a collection that is unordered and unindexed. Sets are written with curly brackets. >>> fruits = {’durian’, ’papaya’, ’banana’} >>> fruits set([’papaya’, ’banana’, ’durian’]) The order of elements could be different than originally entered. Indexing does not work because the set is unordered. >>> fruits[0] Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: ’set’ object does not support indexing © Muním Zabidi 50
  • 51. Manipulating Sets 1/2 Once a set is created, you cannot change its items, but you can add items. Use add() to add 1 item Use update() to add more than 1 item. >>> fruits = {’durian’, ’papaya’, ’banana’} >>> fruits.add(’kiwi’) >>> fruits set([’kiwi’, ’papaya’, ’banana’, ’durian’]) >>> fruits.update(["mango", "guava"]) >>> fruits set([’kiwi’, ’papaya’, ’durian’, ’mango’, ’guava’, ’banana’]) © Muním Zabidi 51
  • 52. Manipulating Sets 2/2 You remove an item using remove() or discard(). You can also use the pop() method to remove the first item. Because sets are unordered, you will not know what item that gets popped. >>> fruits = {’durian’, ’papaya’, ’banana’, ’mango’, ’guava’, ’kiwi’} >>> fruits set([’kiwi’, ’papaya’, ’banana’, ’mango’, ’guava’, ’durian’]) >>> fruits.discard(’papaya’) >>> fruits set([’kiwi’, ’banana’, ’mango’, ’guava’, ’durian’]) >>> fruits.remove(’durian’) >>> fruits set([’kiwi’, ’banana’, ’mango’, ’guava’]) >>> fruits.pop() ’kiwi’ >>> fruits set([’banana’, ’mango’, ’guava’]) © Muním Zabidi 52
  • 53. Dictionaries A dictionary is a collection that is unordered, changeable and indexed. It is also called the hash data structure. Dictionaries are written with curly brackets, and they have keys and values. The key is the index pointing to the value. >>> bike = { ... "brand": "Suzuki", ... "model": "Hayabusa", ... "year" : 1999 ... } >>> >>> >>> bike {’brand’: ’Suzuki’, ’model’: ’Hayabusa’, ’year’: 1999} The items of a dictionary is accessing using its key name, inside square brackets: >>> bike[’model’] ’Hayabusa’ © Muním Zabidi 53
  • 54. Manipulating Dictionaries You can change the value of a specific item by referring to its key name: >>> bike[’year’] = 2000 >>> bike {’brand’: ’Suzuki’, ’model’: ’Hayabusa’, ’year’: 2000} Adding an item to the dictionary is done by using a new index key and assigning a value to it: >>> bike[’color’] = "red" >>> bike {’color’: ’red’, ’brand’: ’Suzuki’, ’model’: ’Hayabusa’, ’year’: 2000} The del keyword removes the item with the specified key name: >>> bike = { "brand": "Suzuki", "model": "Hayabusa", "year" : 1999 } >>> del bike[’model’] >>> bike {’brand’: ’Suzuki’, ’year’: 1999} © Muním Zabidi 54
  • 55. pop and popitem The pop() method removes the item with the specified key name. The popped value can be saved. >>> bike = { "brand": "Suzuki", "model": "Hayabusa", "year" : 1999 } >>> bike.pop("model") ’Hayabusa’ >>> make = bike.pop(’brand’) >>> make ’Suzuki’ >>> bike {’year’: 1999} The popitem() method removes the last inserted item In versions before 3.7, a random item is removed instead >>> bike = { "brand": "Suzuki", "model": "Hayabusa", "year" : 1999 } >>> bike.popitem() (’year’, 1999) >>> bike {’brand’: ’Suzuki’, ’model’: ’Hayabusa’} © Muním Zabidi 55
  • 56. Iterating Through Collections List/Tuple/Set Using Loops You can loop through a list, tuple or set by using a for loop. >>> mammals = [ ’elephant’, ’monkey’, ’bat’, ’tiger’, ’tapir’ ] >>> for animal in mammals: ... print(animal) ... elephant monkey bat tiger tapir © Muním Zabidi 56
  • 57. Iterating Through Dictionaries Iterating through a dictionary using for loops is more interesting. >>> bike = { ... "brand":"Suzuki", ... "model":"Hayabusa", ... "year":1999 ... } >>> # Print all keys >>> for x in bike: ... print(x) ... brand model year >>> # Print all values >>> for x in bike: ... print(bike[x]) ... Suzuki Hayabusa 1999 >>> # Print all key:value pairs >>> for x in bike: ... print("%s:%s" %(x, bike[x])) ... brand:Suzuki model:Hayabusa year:1999 © Muním Zabidi 57
  • 58. Iterating Methods The keys(), values and items() iterator methods returns a list of keys, values and (key, value) pairs, respectively. >>> bike = { "brand": "Suzuki", "model": "Hayabusa", "year" : 1999 } >>> bike.keys() dict_keys([’brand’, ’model’, ’year’]) >>> bike.values() dict_values([’Suzuki’, ’Hayabusa’, 1999]) >>> bike.items() dict_items([(’brand’, ’Suzuki’), (’model’, ’Hayabusa’), (’year’, 1999)]) >>> for x,y in bike.items(): ... print(x,y) ... brand Suzuki model Hayabusa year 1999 © Muním Zabidi 58
  • 60. Syntax Errors >>> print (1/) File "<stdin>", line 1 print (1/) ^ SyntaxError: invalid syntax The parser repeats the offending line and arrows indicate where the syntax error was detected. Make the correction below and run your code again: >>> print (1/0) Traceback (most recent call last): File "<stdin>", line 1, in <module> ZeroDivisionError: division by zero This time, you’ll get an exception. © Muním Zabidi 60
  • 61. Exception Examples TypeError exception: >>> 2 + "2" Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: unsupported operand type(s) for +: ’int’ and ’str’ NameError exception: >>> 2 + 2*x Traceback (most recent call last): File "<stdin>", line 1, in <module> NameError: name ’x’ is not defined © Muním Zabidi 61
  • 62. Basic Exception Handling try, except, else, and finally keywords are used. >>> try: ... print(foo) ... except: ... print("An exception has occurred") ... An exception has occurred © Muním Zabidi 62
  • 63. Multiple Exceptions One block, one error type: try: print(1/0) except ZeroDivisionError: print("You cannot divide a value with zero"") except: print("Something else went wrong") © Muním Zabidi 63
  • 64. Multiple Exceptions If no errors at all, run else block: try: print("Hello") except: print("Something went wrong") else: print("Nothing went wrong") © Muním Zabidi 64
  • 65. Multiple Exceptions finally block executed regardless of error status: try: print("Hello") except: print("Something went wrong") finally: print("The ’try except’ is finished") © Muním Zabidi 65
  • 66. Practical Example Save this file as trywrite.py path = ’data.txt’ try: fp = open(path) try: fp.write(’Zam zam alakazam’) except: print("Unable to write.") finally: fp.close() except: print(f"File {path} is not found!") Run: % python3 trywrite.py File data.txt is not found! Create a blank file called data.txt at the Linux prompt and rerun the script. % touch data.txt % python3 trywrite.py Unable to write. © Muním Zabidi 66