Curs 4
Curs 4
Course 4
EXCEPTIONS
Exceptions in Python have the following form:
Python 3.x Python 3.x
try: try:
#code x = 5 / 0
except: except:
#code that will be executed in print("Exception")
#case of any exception
Output
Exception
EXCEPTIONS
Exceptions in Python have the following form:
Python 3.x Python 3.x
try: try:
#code x = 5 / 1
except: except:
#code that will be executed in print("Exception")
#case of any exception else:
else: print("All ok")
#code that will be executed if
#there is no exception
Output
All ok
EXCEPTIONS
All exceptions in python are derived from BaseException class. There are multiple
types of exceptions including: ArithmeticError, BufferError, AttributeError,
FloatingPointError, IndexError, KeyboardInterrupt, NotImplementedError,
OverflowError, IndentationError, and many more.
A list of all the exceptions can be found on:
https://docs.python.org/3.8/library/exceptions.html#Exception
https://docs.python.org/3.9/library/exceptions.html#Exception
A custom (user-defined) exception type can also used (more on this topic at
“Classes”).
EXCEPTIONS
Exceptions in Python have the following form:
Python 3.x Python 3.x
try: def Test (y):
#code try:
except ExceptionType1: x = 5 / y
#code for exception of type 1 except ArithmeticError:
except ExceptionType2: print("ArithmeticError")
#code for exception of type 1 except:
except: print("Generic exception")
#code for general exception else:
else: print("All ok") Output
#code that will be executed if
ArithmeticError
#there is no exception Test(0)
Generic exception
Test("aaa")
All ok
Test(1)
EXCEPTIONS
Exceptions in Python have the following form:
Python 3.x Python 3.x
try: def Test (y):
#code try:
except ExceptionType1: x = 5 / y
#code for exception of type 1 except:
except ExceptionType2: print("Generic exception")
#code for exception of type 1 except ArithmeticError:
except: print("ArithmeticError")
#code for general exception else:
else: print("All ok")
#code that will be executed if
Generic exception must be
#there is no exception Test(0)
the last one. Code will not
Test("aaa")
compile.
Test(1)
EXCEPTIONS
Python also have a finally keyword that can be used to executed something at the
end of the try block.
Python 3.x Python 3.x
try: def Test (y):
#code try: Output
except: x = 5 / y Test(0):
#code for general exception except: Error
else: print("Error") Final
#code that will be executed else:
#if there is no exception print("All ok") Test(1):
finally: finally: All ok
#code that will be executed print("Final") Final
#after the try block execution Test(0)
#is completed Test(1)
EXCEPTIONS
Python also have a finally keyword that can be used to executed something at the
end of the try block.
Python 3.x Python 3.x
try: def Test (y):
#code try: Finally must be the last
except: x = 5 / y statement
#code for general exception except:
else: print("Error")
#code that will be executed finally:
#if there is no exception print("Final")
finally: else:
#code that will be executed print("All ok")
#after the try block execution Test(0)
#is completed Test(1)
EXCEPTIONS
Exceptions in Python have the following form:
Python 3.x Python 3.x
try: def Test (y):
#code try:
except (Type1,Type2,…Typen): x = 5 / y
#code for exception of type except (ArithmeticError,TypeError):
#1,2,… print("ArithmeticError")
except: except:
#code for general exception print("Generic exception")
else: else:
#code that will be executed print("All ok") Output
#if there is no exception
ArithmeticError
Test(0)
ArithmeticError
Test("aaa")
All ok
Test(1)
EXCEPTIONS
Exceptions in Python have the following form:
Python 3.x Python 3.x
try: try:
#code x = 5 / 0
except Type1 as <var_name>: except Exception as e:
#code for exception of type print( str(e) )
#1.
except:
#code for general exception
else: Output
#code that will be executed
division by 0
#if there is no exception
EXCEPTIONS
Exceptions in Python have the following form:
Python 3.x
try:
#code
except (Type1,Type2,…Typen) as <var>:
#code for exception of type 1,2,… n
try:
x = 5 / 0
except (Exception,ArithmeticError,TypeError) as e:
print( str(e), type(e) )
Output
Python3: division by zero <class 'ZeroDivisionError'>
EXCEPTIONS
Python also has another keyword (raise) that can be used to create / throw an
exception:
Python 3.x
raise ExceptionType (parameters)
raise ExceptionType (parameters) from <exception_var>
try:
raise Exception("Testing raise command")
except Exception as e:
print(e)
Output
Testing raise command
EXCEPTIONS
Each exception has a list of arguments (parameter args)
Python 3.x
try:
raise Exception("Param1",10,"Param3")
except Exception as e:
params = e.args
print (len(params))
print (params[0])
Output
3
Param1
EXCEPTIONS
raise keyword can be used without parameters. In this case it indicates that the
current exception should be re-raised.
Python 3.x
try:
try:
x = 5 / 0
except Exception as e:
print(e)
raise
except Exception as e:
print("Return from raise -> ",e)
Output
Traceback (most recent call last):
File "a.py", line 2, in <module>
x=5/0
ZeroDivisionError: division by zero
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "a.py", line 4, in <module>
raise Exception("Error") from e
Exception: Error
EXCEPTIONS
Python has a special keyword (assert) that can be used to raise an exception based
on the evaluation of a condition:
Python 3.x
age = -1
try:
assert (age>0),"Age should be a positive number"
except Exception as e:
print (e)
Output
Age should be a positive number
EXCEPTIONS
pass keyword is usually used if you want to catch an exception but do not want to
process it.
Python 3.x
try:
x = 10 / 0
except:
pass
Some exceptions (if not handled) can be used for various purposes.
Python 3.x
This exception (SystemExit) if Output
print("Test") not handle will imediatelly
raise SystemExit Test
terminate your program
print("Test2")
MODULES
Modules are python’s libraries and extends python functionality. Python has a special
keyword (import) that can be used to import modules.
Format (Python 3.x)
import module1,[module2,module3, … modulen]
Classes or items from a module can be imported separately using the following
syntax.
Format (Python 3.x)
from module import object1,[object2,object3, … objectn]
from module import *
When importing a module aliases can also be made using “as” keyword
Format (Python 3.x)
import module1 as alias1,[module2 as alias2, … modulen as aliasn]
MODULES
Python has a lot of default modules (os, sys, re, math, etc).
There is also a keyword (dir) that can be used to obtain a list of all the functions and
objects that a module exports.
Format (Python 3.x)
import math
print ( dir(math) )
The list of functions/items from a module may vary from Python 2.x to Python 3.x and
from version to version, or from different versions of Python.
MODULES
Python distribution modules:
o Python 3.x ➔ https://docs.python.org/3/py-modindex.html
Module Purpose Module Purpose
collections Implementation of different containers re Regular expression implementation
ctype Packing and unpacking bytes into c-like random Random numbers
structures
socket Low-level network interface
datetime Date and Time operators
subprocess Processes
email Support for working with emails
sys System specific functions (stdin,stdout,
hashlib Implementation of different hashes (MD5, SHA, arguments, loaded modules, …)
…)
traceback Exception traceback
json JSON encoder and decoder
urllib Handling URLs / URL requests, etc
math Mathematical functions
xml XML file parser
os Different functions OS specific (make dir,
delete files, rename files, paths, …)
MODULES - SYS
Python documentation page:
o Python 3.x ➔ https://docs.python.org/3/library/sys.html#sys.modules
object Purpose
sys.argv A list of all parameters send to the python script
sys.platform Current platform (Windows / Linux / MAC OSX)
sys.stdin Handlers for default I/O operations
sys.stdout,
sys.stderrr
sys.path A list of strings that represent paths from where module will be loaded
sys.modules A dictionary of modules that have been loaded
MODULES - SYS
sys.argv provides a list of all parameters that have been send from the command line
to a python script. The first parameter is the name/path of the script.
Output
>>> python.exe C:\test.py
First parameter is C:\test.py
MODULES - SYS
Python 3.x (File: sum.py)
import sys
suma = 0
try:
for val in sys.argv[1:]:
suma += int(val)
print("Sum=",suma)
except:
print("Invalid parameters")
Output
>>> python.exe C:\sum.py 1 2 3 4
Sum = 10
Output
['$Recycle.Bin', 'Android', 'Documents and Settings', 'Drivers', 'hiberfil.sys', 'Program Files', 'Program Files (x86)', 'ProgramData',
'Python27', 'Python38', 'System Volume Information', 'Users', 'Windows‘, …]
Output
os module can also be used to execute a system .\a
command or run an application via system function .\a.py
.\all.csv
Python 3.x .\run.bat
.\Folder1\version.1.6.0.0.txt
import os .\Folder1\version.1.6.0.1.txt
os.system("dir *.* /a") .\Folder1\Folder2\version.1.5.0.8.txt
INPUT/OUTPUT
Python has 3 implicit ways to work with I/O:
A) IN: via keyboard (with input or raw_input keywords)
There are several differences between python 2.x and python 3.x regarding reading from stdin
Python 3.x
>>> print (“test”) >>> print (“test”,10)
test test 10
>>> print (“test”,10,sep=“---”) >>> print (“test”);print(“test2”)
test---10 test
test2
>>> print (“test”,end=“***”);print(“test2”)
test***test2
FILE MANAGEMENT
A file can be open in python using the keyword open.
Format (Python 3.x)
FileObject = open (filePath, mode='r', buffering=-1, encoding=None,
errors=None, newline=None, closefd=True, opener=None)
Lines read using this method contain the line-feed terminator. To remove it, use strip or
rstrip methods.
FILE MANAGEMENT
Functional programming can also be used:
Python 3.x
x = [line for line in open("file.txt") if "Gen" in line.strip()]
print (len(x))