Functions (very basic)#
Education objectives
defsimple arguments
docstring
return
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.
Duck typing
In computer programming, duck typing is an application of the duck test—“If it walks like a duck and it quacks like a duck, then it must be a duck”—to determine whether an object can be used for a particular purpose
Duck typing on Wikipedia
def add(arg0, arg1):
"""Print and return the sum of the two arguments (duck typing)."""
result = arg0 + arg1
print("result = ", result)
return result
add(2, 3)
result = 5
5
add("a", "b")
result = ab
'ab'
Exercise 16
Write a function that returns the sum of the first argument with twice the second argument.
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
"""
...
Solution to Exercise 16
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
16
add_second_twice("a", "b")
arg0 + 2*arg1 = a + 2*b = abb
'abb'
Exercise 17 (Parsing file0.n.txt)
Same exercise as Parsing file0.1.txt but process many files and print file base
statistics and overall statistics:
Example of output
python3 step0.2.py
file = "../data/file0.1.txt"
nb = 78 ; sum = 42.46 ; avg = 0.54
file = "../data/file0.2.txt"
nb = 100 ; sum = 53.29 ; avg = 0.53
file = "../data/file0.3.txt"
nb = 25 ; sum = 12.72 ; avg = 0.51
# total over all files:
nb = 203 ; sum = 108.47 ; avg = 0.53
The first step consist in taking the code from the previous parsing exercise and create a function that takes a filename as input and print the statistics:
def compute_stats(file_name):
"""computes the statistics of data in file_name
:param file_name: the name of the file to process
:type file_name: str
:return: the statistics
:rtype: a tuple (number, sum, average)
"""
pass
This function can simply be called for each file.
Solution to Exercise 17 (Parsing file0.n.txt)
#!/usr/bin/python3
"""computes basic statistics on file
that contains a set of lines, each line containing
one float
"""
def compute_stats(file_name):
"""
computes the statistics of data in file_name
:param file_name: the name of the file to process
:type file_name: str
:return: the statistics
:rtype: a tuple (number, sum, average)
"""
total_sum = 0.0
number = 0
with open(file_name) as handle:
for line in handle:
elem = float(line)
total_sum += elem
number += 1
return (number, total_sum, total_sum / float(number))
base_path = "../common/data_read_files"
file_names = [
f"{base_path}/file0.1.txt",
f"{base_path}/file0.2.txt",
f"{base_path}/file0.3.txt",
]
# equivalent to
# file_names = ['{}/file0.{}.txt'.format(base_path, x) for x in range(1, 4)]
numbers = []
sums = []
for file_name in file_names:
(local_number, local_sum, local_avg) = compute_stats(file_name)
numbers.append(local_number)
sums.append(local_sum)
for index, file_name in enumerate(file_names):
print(
f"file = {file_name}\n"
f"nb = {numbers[index]:<5}; "
f" sum = {sums[index]:<7,.2f}; "
f"avg = {sums[index] / numbers[index]:<5,.2f}"
)
# equivalent to
# for (file_name, local_number, local_sum) in zip(file_names, numbers, sums):
# print('file = "{}"\nnb = {:<5}; sum = {:<7,.2f}; avg = {:<5,.2f}'.format(
# file_name, local_number, local_sum,
# local_sum/local_number))
all_sum = sum(sums)
all_numbers = sum(numbers)
print(
"# total over all files:\nnb = {: <5}; sum = {:<7,.2f}; avg = {:.2f}".format(
all_numbers, all_sum, all_sum / all_numbers
)
)
file = ../common/data_read_files/file0.1.txt
nb = 78 ; sum = 42.46 ; avg = 0.54
file = ../common/data_read_files/file0.2.txt
nb = 100 ; sum = 53.29 ; avg = 0.53
file = ../common/data_read_files/file0.3.txt
nb = 25 ; sum = 12.72 ; avg = 0.51
# total over all files:
nb = 203 ; sum = 108.47 ; avg = 0.53