Chapter 4 PPT
Chapter 4 PPT
Chapter 4 PPT
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
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
print_args(arg1,arg2,*args,kwarg1,kwarg2,**kwargs,kwargs99):
^
SyntaxError: invalid syntax
Exercises
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
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__)
if __name__ == '__main__':
main(sys.argv[1]) # first argument (index 0) is always the
name of the file that is being executed