How does Python "read in" a program when you run it? For example, I don't understand why there wouldn't be a NameError: name 'cough' is not defined
in the below code:
def main():
for i in range(3):
cough()
def cough():
print('cough')
if __name__ == '__main__':
main()
Basically, my question can also be stated as why do the above and below programs output the same thing:
def cough():
print('cough')
def main():
for i in range(3):
cough()
if __name__ == '__main__':
main()
Python is an interpreted language which is executed statement by statement (thanks to viraptor's tip: when compiling to bytecode it happens on whole file + per function)
In this case below the program reads line by line and knows that the function cough()
and main()
are defined. and later when main()
is called Python knows what it is and when main()
calls cough()
Python knows what it is as well.
def cough():
print('cough')
def main():
for i in range(3):
cough()
if __name__ == '__main__':
main()
In this other case (below) it is the same thing. just that Python learns what main()
function is before cough()
. Here you might wonder: "why won't python throw an error since it doesn't know what caugh()
is inside main()
? " Good question my friend.
But as long as your function is defined before you call it everything is fine. Because remember Python won't "check" if a function is defined until you call it. so in this case even tho cough()
is not defined when python is reading function main()
it is ok because we didn't call main()
until after cough()
is defined below.
def main():
for i in range(3):
cough()
def cough():
print('cough')
if __name__ == '__main__':
main()
Hope this helps you understand Python better.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With