In my code below, I am defining two functions. main and cube. I wanted main to be the start of my program, so I called cube inside of main:
>>> def main():
number = int(input('Enter a number: '))
cubed_number = cube(number)
print("The number cubed is: ", cubed_number)
>>> def cube(number):
return number * number * number
>>>
But I'm defining cube after main, so I thought my code would raise a NameError. However, instead of an exception being raised, Python executed my code perfectly fine:
>>> main()
Enter a number: 5
The number cubed is: 125
>>>
What happened? Why was Python able to run my code, without knowing how cube was defined yet? Why wasn't a NameError raised?
Even stranger is that when I tried to do the samething with classes, Python did raise a NameError:
>>> class Main:
cubed_number()
Traceback (most recent call last):
File "<pyshell#27>", line 1, in <module>
class Main:
File "<pyshell#27>", line 2, in Main
cubed_number()
NameError: name 'cubed_number' is not defined
>>>
What's happening here?
Note: This is not a duplicate of Why can I call a function before defining it, with only a warning?, because the answers there don't really explain why or how this behavior works in Python. I created this Q&A because the current answers for questions such as this are scattered across various questions. I also feel it would be beneficial to show what is happening behind the scenes for this to work. Feel free to edit and improve the Q&A.