A training to acquire strong basis in Python to use it efficiently
Pierre Augier (LEGI), Cyrille Bonamy (LEGI), Eric Maldonado (Irstea), Franck Thollard (ISTerre), Christophe Picard (LJK), Loïc Huder (ISTerre)
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.
Function blocks begin with the keyword def
followed by the function name and parentheses (()
).
def print_hello():
"hello printer"
print('hello')
def myprint(s):
"my hello printer"
print('I print', s)
# 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
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 as return None
.(Note: Wikipedia about duck typing: https://fr.wikipedia.org/wiki/Duck_typing)
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'
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
"""
pass
A solution:
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
add_second_twice(4, 6)
arg0 + 2*arg1 = 4 + 2*6 = 16
16
myfunc('a', 'b')
What does it means correct ?
How to define correct ?
The code crashes .. is this function suspect ?
A solution: TESTING !