Functions#
(Click here for the German version of this page)
First things first: Unlike programming languages such as Java or C, there is no dedicated main function in Python. The contents of the main function are written and executed in the global space of the file. When working with Python professionally, this is not desired and is circumvented. But for this introduction, this does not matter.
Creation of a function#
To define a function, the keyword def
i used.
Afterwards, the function receives a name, and the parameters are defined with round brackets.
The function signature is then terminated with a colon. After the colon, the code block with the contents of the function, is indented.
Example:
def i_print_in_reverse(input_string):
result = ""
for i in range(1, len(input_string)+1):
result += input_string[-i] # The "+" operator denotes concatenation for strings
print(result)
i_print_in_reverse("Hello World!")
# !dlroW olleH
More generally:
def function_name(parameter1, parameter2, ...):
<Function body>
It is also possible to define default values for parameters. For this, parameters are assigned values in the function signature. As soon as one default value is assigned, all parameters to the right also require default values.
Example:
def sum_of_up_to_four_numbers(a, b, c=0, d=0):
return a + b + c + d
print(sum_of_up_to_four_numbers(1,2))
# --> 3
print(sum_of_up_to_four_numbers(1,2,3))
# --> 6
print(sum_of_up_to_four_numbers(1,2,3,4))
# --> 10
Return values#
The keyword return
is used to specify what should be returned from a function. A unique property of Python is that a function may have multiple return values.
Assuming one wants to create a function, which takes a lowercase word as an argument and should output how many vowels and consonants are present in the string. Additionally, the function should output whether there are less vowels than consonants as a Boolean.
Other programming languages would have to define a data structure for this return value, so that two integers and one Boolean can be returned. In Python one can just specify those three values, separated by commas, as the return value.
def vowels_and_consonants(input_string):
vowels_count = 0
consonants_count = 0
for letter in input_string: # One can iterate over strings just like with lists
if letter in ["a", "e", "i", "o", "u"]:
vowels_count += 1
else:
consonants_count += 1
return vowels_count, consonants_count, vowels_count < consonants_count
vowels_count, consonants_count, there_are_more_consonants = vowels_and_consonants("algorithm")
print(vowels_count)
# --> 3
print(consonants_count)
# --> 6
print(there_are_more_consonants)
# --> True
One can look back to Python’s way of handling multiple assignments in one statement. Since the function returns three values and three variables are present on the left side of the assignment, this is a valid assignment.
Recursion#
Recursion works in Python just like in any other programming language. A function is recursive if it calls itself. For example, a recursive calculation of the n-th Fibonacci number:
def fib_rec(n):
if n <= 1:
return n
else:
return fib_rec(n-1) + fib_rec(n-2)
print(fib_rec(6))
# --> 8
Exercise#
Please create a function, which takes a positive integer as argument and returns True
if the number is even. It should return False
otherwise. Please test the function for a few numbers of your choosing. You do not have to make sure that really a positive integer was input. You may assume that only positive integers are used as input. Feel free to find multiple possible solutions.
# Here you can write your code...
Solution
Probably the most common solution using the modulo operator:
def is_even_ordinary(value):
if value % 2 == 0:
return True
else:
return False
A more compact version using the modulo operator:
def is_even_ordinary_compact(value):
return value % 2 == 0
An impractical recursive solution. 0
is known as an even number and 1
is known as an odd number. If the current value is not equal to one of those two, the function calls itself recursively with the value subtracted by 2
, until the result is either 0
or 1
. The subtraction by 2
makes the value still be either also even or also odd as the number before.
def is_even_rec(value):
if value == 0:
return True
elif value == 1:
return False
else:
return is_even_rec(value-2)
Idea: Whether an integer is even or odd depends on the last digit. Therefore, it is possible to convert the number into a string and inspect the last digit. If the last digit is 0
, 2
, 4
, 6
or 8
, then it is even. Otherwise, it is odd.
def is_even_last_digit(value):
return int(str(value)[-1]) in [0, 2, 4, 6, 8]
In Python it is also possible to work with individual bits. The &
operator represents a bitwise and. Since the bit sequence …00001
is equivalent to 1
, the length of the left value is irrelevant. Everything apart from the last bit will turn to 0
, therefore only the last bit can be different from zero. For an even number, the last bit is always 0
, therefore the result would be 0 & 1 = 0
. For an odd number, the last bit is always 1
, therefore the result would be 1 & 1 = 1
. 0
and 1
can then be casted to Booleans. 0
will become False
and 1
will become True
. Since the return value would be the opposite currently, the return value can just be negated with the not
keyword.
def is_even_bitwise_and(value):
return not bool(value & 1)
There are many solutions for this task. Here are just some examples with some being more practical than other ones. This should just illustrate the diversity of possible solutions.