In this article we explais how functions work.
- when you invoke a function, Python remembers the place where it happened and jumps into the invoked function;
- the body of the function is then executed;
- reaching the end of the function forces Python to return to the place directly after the point of invocation.
You should bear in mind that you mustn’t invoke a function which is not known at the moment of invocation.
Python reads your code from top to bottom. It’s not going to look ahead in order to find a function you forgot to put before invocation.
If you move the function to the end of the code, Python won’t be able to find the function when the execution reaches the invocation.
For example, we have the next function:
print(«We start now.»)
information()
print(«We end now.»)
def information():
print(«Enter a value: «)
The error message will read is the following:
NameError: name ‘information’ is not defined
You mustn’t have a function and a variable of the same name.
def information():
print(«Enter a value: «)
information = 1
Assigning a value to the name information (name of the function) causes that Python forgets its previous role. The function named information becomes unavailable.
Is not compulsory to put all your functions at the top of your source file, you can mix your code with the functions.
You can modify the prompting message by changing the code in just one place – inside the function’s body. You can see that in the following example:
def information():
print(«Enter a value: «)
information()
a = int(input())
information()
b = int(input())
information()
c = int(input())
©image: https://medium.com/
Contenido Web de Yolanda Muriel está sujeto bajo Licencia Creative Commons Atribución-NoComercial-SinDerivadas 3.0 Unported.

