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...