+ 3
"You must define functions before they are called."
Why is it so? Is there no concept of function prototyping in Python as in C++?
4 odpowiedzi
+ 6
I guess it's harder to learn python after having learnt c++ than c++ after python ^^
In c++ the idea of prototypes is relevant because all the code will be analysed and compiled so you can write the définition of your prototype later and c++ will understand what you are talking about because it will be able to create a link between your prototype and your real function definition.
In python your code is analysed and INTERPRETED line by line, so here it cannot be prototype like in c++ because python would have to analyse the whole code to find where is the real definition of your function... So you have to define the function before you use it, so python will understand what's the function and how does it work and then it will be able to use it.
A good option is to define your functions in differents files and then use the import keyword.
+ 2
Ok so an INTERPRETER used in python is the main problem. That's why something like prototyping is not possible because the interpreter would not be able to find a function's definition immediately at that point and will give an error. Understood!
THANKS ALL!
+ 2
In addition the only moment when you can "call" a function without having defined then is in cases like this :
def a():
b() # b is a function not defined
a() # here it will failed because b is not defined
def b():
print("Yep")
a() #here it's okay.
You can write the b() in the a definition and it works perfectly only because b is not called while defining the a function so it allows you to so it.
But this will not solve your problem of prototypes... The solution to have a clean code ia to use modules.
+ 2
i you don't want to do something with your functions at that point you could just pass it like this
def MyCall():
pass
MyCall() #wont give any error cause it as been passed
but the baseline is you definitely have to define it first if you call it like this you wont get any error only that no action is happening