Functions in Python
Look at this excerpt from a PythonA high-level programming language. role-playing game programSequences of instructions for a computer. 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 functionA section of code that, when programming, can be called by another part of the program with the purpose of returning one single value. is named and written, it can be callingStarting or running a function or procedure. at any point in the programSequences of instructions for a computer..
To call a function in PythonA high-level programming language., 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)