Module 4 - Section 1 - While and Functions
Module 4 - Section 1 - While and Functions
4.1.5 - Function Arguments
Functions can take parameters or arguments. These can be used to increase the flexibility of a function by altering what it does based on parameters passed to it. For example, write the following function to Thonny script editor and save it as printMyName.
def hello(name):
print("Hello " + name)
after that execute the code (press the play button) and inside the CLI area write :
>>> hello("Bob")
>>> hello("Alice")
The definition of the hello() function in this program has a parameter called name A parameter is a variable that an argument is stored in when a function is called. The first time the hello() function is called, it’s with the argument 'Bob'. The program execution enters the function, and the variable name is automatically set to 'Bob', which is what gets printed by the print() statement.
One special thing to note about parameters is that the value stored in a parameter is forgotten when the function returns. For example, if you added print(name) after hello('Alice') in the previous program, the program would give you a NameError because there is no variable named name. This variable was destroyed after the function call hello('Alice') had returned, so print(name) would refer to a name variable that does not exist.
This is similar to how a program’s variables are forgotten when the program terminates.