Functions

Oliver Irwin

16th March 2023

Objectives

  • define the concept of function
  • recognise functions in code
  • implement functions to extend your code

Context

You have seen that writing code can be a tedious task

(especially if you have to repeat the same instructions in different contexts)

We need to find a way to simplify writing code

Functions

Functions are used to set aside instructions that should be used at different parts of the program

  • define once
  • use everywhere

Function definition

To def-ine a function, we use the def keyword

A Python function is an element that has:

  • a name
  • a sequence of instructions

and optionnally:

  • parameters
  • a return value invisible text

Function example

def say_hello():
    print("Hello!")
>>> say_hello()
Hello!

Function example - with parameter

def say_hello(name):
    print(f"Hello, {name}")
>>> say_hello("Bob")
Hello, Bob

Transforming values

You can use functions to create new values or transform existing ones

To do this, you can use the return keyword

Careful! The return keyword stops the execution of the function

Creating a value example

def create_player(name, player_class):
    return {"name": name, "class": player_class, "xp": 0}
>>> create_player("Ned Stark", "Warden")
{"name": "Ned Stark", "class": "Warden", "xp": 0}

Transforming values example

def add_two(number):
    number = number + 2
    return number
>>> add_two(14)
16

What to do with a returned value ?

Most times, when you create or use a function that returns a value, you want to store it in a variable

You saw this with the input function!

>>> new_value = add_two(14)
>>> nb_lives = 5
>>> nb_lives = remove_life(nb_lives)
>>> print(nb_lives)
4