Functions (very basic)
A function is a block of organized, reusable code that is used to perform a single, related action. Functions provide better modularity for your application and a high degree of code reusing.
Simple function definitions and calls¶
Function blocks begin with the keyword def followed by the function name and
parentheses (()).
The code block within every function starts with a colon (:) and is indented.
Any input parameters or arguments should be placed within these parentheses.
def print_hello():
"hello printer"
print("hello")
def myprint(my_var):
"my hello printer"
print("I print", my_var)
# function calls
print_hello()
print_hello()
myprint("First call of myprint")
myprint("Second call of myprint")hello
hello
I print First call of myprint
I print Second call of myprint
The first statement of a function can be the documentation string of the function, also called “docstring”.
The statement
return [expression]exits a function, optionally passing back an expression to the caller. No return statement or a return statement with no arguments is the same asreturn None.
def add(arg0, arg1):
"""Print and return the sum of the two arguments (duck typing)."""
result = arg0 + arg1
print("result = ", result)
return resultadd(2, 3)result = 5
5add("a", "b")result = ab
'ab'Solution to Exercise 1
def add_second_twice(arg0, arg1):
"""Return the sum of the first argument with twice the second one.
Arguments should be of type that support sum and product by
an integer (e.g. numerical, string, list, ...)
:param arg0: first argument
:param arg1: second argument
:return: arg0 + 2 * arg1
"""
result = arg0 + 2 * arg1
print(f"arg0 + 2*arg1 = {arg0} + 2*{arg1} = {result}")
return result
assert 13 == add_second_twice(3, 5)
assert "aabbbb" == add_second_twice("aa", "bb")
assert [1, 2, 3, 4, 3, 4] == add_second_twice([1, 2], [3, 4])
add_second_twice(4, 6)arg0 + 2*arg1 = 3 + 2*5 = 13
arg0 + 2*arg1 = aa + 2*bb = aabbbb
arg0 + 2*arg1 = [1, 2] + 2*[3, 4] = [1, 2, 3, 4, 3, 4]
arg0 + 2*arg1 = 4 + 2*6 = 16
16add_second_twice("a", "b")arg0 + 2*arg1 = a + 2*b = abb
'abb'Solution to Exercise 2
treat_files_simple.py
#!/usr/bin/python3
"""computes basic statistics (size, sum and average) on files
containing lines with one float.
"""
def compute_stats(path):
"""
computes the statistics of data in a file.
:param path: the path of the file to process
:type path: str
:return: the statistics
:rtype: a tuple (size, sum, average)
"""
total_sum = 0.0
size = 0
with open(path, encoding="utf-8") as handle:
for line in handle:
elem = float(line)
total_sum += elem
size += 1
return (size, total_sum, total_sum / float(size))
file_paths = [f"../file0.{i}.txt" for i in range(1, 4)]
sizes = []
sums = []
for file_path in file_paths:
(file_size, file_sum, file_avg) = compute_stats(file_path)
sizes.append(file_size)
sums.append(file_sum)
for index, file_path in enumerate(file_paths):
print(
f"file = {file_path}\n"
f"size = {sizes[index]:<5}; "
f" sum = {sums[index]:<7,.2f}; "
f"avg = {sums[index] / sizes[index]:<5,.2f}"
)
all_sum = sum(sums)
all_sizes = sum(sizes)
avg = all_sum / all_sizes
print(
f"# total over all files:\nsize = {all_sizes: <5};"
f" sum = {all_sum:<7,.2f}; avg = {avg:.2f}"
)