Procedures and functionsFunctions in Python

When writing programs, we should avoid long, repetitive code. Procedures and functions help to keep our programs simple and short.

Part ofComputer ScienceProgramming

Functions in Python

Look at this excerpt from a role-playing game which simulates the throwing of a dice:

import random
sides = int(input("How many sides does the dice have?"))
number = random.randint(1,sides)
print(number)

Imagine that there is a need to simulate dice throwing many times in this game. A function could be used, rather than typing in this same code repeatedly throughout the program.

Writing a function in Python

To create a function, first give the function a name, and name the value that the function should use in its calculations. A good name for the dice-rolling function could be ‘roll_dice’.

Since you want to be able to simulate dice with different numbers of sides, a good name for the value to use would be ‘sides’. Python uses the statement def to name a function.

def roll_dice(sides):

The function code is then written indented beneath the def statement. Within this code, the variable that is used to return the random number to the main program must be specified. In this case, it has been named 'number'. Python uses return to bring the result of the calculation back to the main program.

import random
def roll_dice(sides): number = random.randint(1,sides) return(number) sides = int(input("How many sides does the dice have?"))
throw = roll_dice(sides)
print(throw)

Running a function in Python

Once a is named and written, it can be at any point in the .

To call a function in , simply use its name (include the brackets) and the value it needs to use for calculation, plus a variable that the returned value will be stored in – in this case, 'throw'.

throw = rolldice(sides)