0% found this document useful (0 votes)
222 views30 pages

Python Functions and Exception Handling

The document discusses Python functions including defining functions with parameters, returning values, exceptions, and documenting functions with docstrings. Functions are used to group reusable code and are defined using the def keyword followed by the function name and parameters. Exceptions represent events that disrupt normal program flow and can be handled using try, except, and finally blocks.

Uploaded by

id
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
222 views30 pages

Python Functions and Exception Handling

The document discusses Python functions including defining functions with parameters, returning values, exceptions, and documenting functions with docstrings. Functions are used to group reusable code and are defined using the def keyword followed by the function name and parameters. Exceptions represent events that disrupt normal program flow and can be handled using try, except, and finally blocks.

Uploaded by

id
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd

Chapter 4

Python Fundamentals
Functions
• Used for grouping instructions that are executed multiple times in
the same application/script
• Reserved keyword for definition: def
• Function signature is composed from:
def function_name(parameters): #the parameters are optional
... instruction_set
... return result of the function # functions don’t necessary return
a value
Function implementation

>>> def square(x):


... return x*x
...
>>> square(5)
25
• Execute the instructions from above in both REPL and PyCharm. What’s the
noticeable difference?
Function implementation

>>> def odd_or_even (n):


... if n % 2 == 0:
... print(“even")
... return # when there is no actual value after the return keyword, we receive
a None value
... print(“odd")
...
>>> odd_or_even(4)
even
>>> odd_or_even(5)
odd
>>>
Functions parametrization
• Our defined functions can have one or multiple parameters, without
having to specify their type, as the language itself is dynamic
def sum_function(a, b):
print(a + b)
• Based on the definition from above, we can call the function with
multiple types of parameters
sum_function(10, 5)
sum_function(20.7, 13.2)
sum_function([1, 2, 3], [4, 5, 6])
sum_function(“Telecom”, “ Academy”)
Q: What will be displayed after the following statement?
sum_function (10.2, “7”)
Parameters with default values
Parameters with default values

>>> def banner(message, border='-'):


... line = border * len(message)
... print(line)
... print(message)
... print(line)
...
>>> banner("Norwegian Blue")
--------------
Norwegian Blue
--------------
Parameters with default values

>>> banner("Sun, Moon and Stars", "*")


*******************
Sun, Moon and Stars
*******************

>>> banner(border=".",message="Hello from Earth")


................
Hello from Earth
................
Returning data from a function
• We are using the return keyword
• We don’t need to specify the returned data-type
• We can return multiple values from the function – they will be
grouped as a tuple
def evaluate (x):
square = x ** 2
cube = x ** 3
return square, cube

rez = evaluate(5)
rez[0] = 25
rez[1] = 125
Positional arguments and key-word arguments
Multiple positional arguments
*args – gives us the possibility to pass multiple positional
arguments, without specifying exactly how many

>>> def hypervolume(*args):


... print(args)
... print(type(args))
>>> hypervolume(3,4)
(3, 4)
<class 'tuple'>
>>> hypervolume(3,4,5)
(3, 4, 5)
<class 'tuple'>
Multiple key-word arguments
**kwargs – gives us the possibility to pass multiple key-word arguments to a
function

>>> def tag(name,**kwargs):


... print(name)
... print(kwargs)
... print(type(kwargs))
...
>>> tag('img',src="monet.jpg",alt="Sunrise by Claude Monet",border=1)
img
{'src': 'monet.jpg', 'border': 1, 'alt': 'Sunrise by Claude Monet'}
<class 'dict'>
Multiple arguments in a function
>>> def print_args(**kwargs,*args):
File "<stdin>", line 1
def print_args(**kwargs,*args):
^
SyntaxError: invalid syntax
Multiple arguments in a function
>>> def print_args(arg1,arg2,*args):
... print(arg1)
... print(arg2)
... print(args)
...
>>> print_args(1,2,3,4,5)
1
2
(3, 4, 5)
Multiple arguments in a function
>>> def print_args(arg1,arg2,*args,kwarg1,kwarg2):
... print(arg1)
... print(arg2)
... print(args)
... print(kwarg1)
... print(kwarg2)
...
>>> print_args(1,2,3,4,5,kwarg1=6,kwarg2=7)
1
2
(3, 4, 5)
6
7
Multiple arguments in a function
>>> print_args(1,2,3,4,5,6,7)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: print_args() missing 2 required keyword-only
arguments: 'kwarg1' and 'kwarg2'
>>>
Multiple arguments in a function
>>> def print_args(arg1,arg2,*args,kwarg1,kwarg2,**kwargs):
... print(arg1)
... print(arg2)
... print(args)
... print(kwarg1)
... print(kwarg2)
... print(kwargs)
>>> print_args(1,2,3,4,5,kwarg1=6,kwarg2=7,kwarg3=8,kwarg4=9)
1
2
(3, 4, 5)
6
7
{'kwarg3': 8, 'kwarg4': 9}
Multiple arguments in a function
>>>
print_args(arg1,arg2,*args,kwarg1,kwarg2,**kwargs,kwargs99):
File "<stdin>", line 1

print_args(arg1,arg2,*args,kwarg1,kwarg2,**kwargs,kwargs99):
^
SyntaxError: invalid syntax
Exercises

1.Write a function, named min_list, that receives a list as an argument


and returns the minimum value in that list. Modify the function to also
return the maximum value if desired.
2.Write a function, named sum_list that receives a list as an argument
and returns the sum of that list.
3.Write a function, named order_list that receives a list as an argument
and returns in ascending order.
Exceptions
• They represent events that are not allowed in our program
• By default, they can block the execution of our program if they are
not managed (unlike errors)
• We can have system exceptions (the ones that are built-in the core
libraries) or application specific exceptions
Exception management in Python
• The most general example for treating exception is

try:
block of code that may generate an exception
except:
block of code executed only when an exception is thrown

• We can have multiple except blocks for the same try block
Try/Except example

x = input(“Value: ”) Q1: What will happen if the input value


y=5 will be 2?
try:
print(“:)”) Q2: What will happen if the input value
z = y/x will be 0?
print(“:(”)
except:
print(“:D”)
Finally block
• Instructions that are defined inside the finally block will be executed no matter what – even if we
have an exception thrown or not

my_list = [“telacad”, “python”, “java”]

try:
my_list=[1] = “microsoft iis”
my_list[4] = “docker”
print(“:)”)

except:
print(“You used an inexistent index”)
finally:
print(“Finished working with my_list”)

Q: What will be the difference in the printed result if we comment out the line which refers to the 4 th
index?
Treating specific exceptions
• We can have multiple except blocks in order to treat multiple
types of exceptions
try:
instructions_block
except ValueError:
print(“You’ve used an invalid value”)
except ZeroDivisonError:
print(“You’ve tried to divide by 0…”)
Raising your own exceptions
• Exceptions can be used in order to implement some constraints in our
applications/scripts
• Raising/throwing of an exception can be done by using the raise
keyword, followed by the exception type and a message
• Ridicarea/aruncarea unei excepții se face cu ajutorul cuvântului cheie
raise urmat de tipul excepției, și un mesaj corespunzător
def square_root(x):
if x < 0:
raise ValueError(“Square root can only be applied on positive values”)
Docstrings
Docstring examples
def function_documentation():
""
The documentation of a function needs to be
maintained in order not to create
confusion for other programmers
"""
pass

print(function_documentation.__doc__)
Example of a function documentation
def square_root(x):
"“”
Calculates the square root of x passed as a parameter
:param x: Integer value;
:return: Float result of the square root operation
:raise: ValueError if x is lower than 0

"""
Using help documentation
>>> import requests
>>> help(requests.get) # sau folosim print(requests.get.__doc__)

get(url, params=None, **kwargs)


Sends a GET request.

:param url: URL for the new :class:`Request` object.


:param params: (optional) Dictionary, list of tuples or bytes to send
in the query string for the :class:`Request`.
:param \*\*kwargs: Optional arguments that ``request`` takes.
:return: :class:`Response <Response>` object
:rtype: requests.Response
Using comments in our programs

• Docstring – the most appropriate way to document a


class/function/block of code
• Comments – useful when commenting what a single line does

if __name__ == '__main__':
main(sys.argv[1]) # first argument (index 0) is always the
name of the file that is being executed

You might also like