Can someone give me a solution to this
dosomething()
def dosomething():
print 'do something'
I don't want my method defines up at the top of the file, is there a way around this?
So in general, yes, the order does matter; there's no hoisting of names in Python like there is in other languages (e.g JavaScript).
Defining a FunctionFunction blocks begin with the keyword def followed by the function name and parentheses ( ( ) ). Any input parameters or arguments should be placed within these parentheses. You can also define parameters inside these parentheses.
It executes the code inside a class only when it is "called", not when it is defined. So, the output should print "Out" first. But here it is printing "Middle" first. This should not happen, as python interpreter when first encounters "Middle" - it is within the definition, and thus should not be executed at that time.
Anywhere in your application that you need to accomplish the task, you simply call the function. Down the line, if you decide to change how it works, then you only need to change the code in one location, which is the place where the function is defined.
The "standard" way is to do things inside a main
function at the top of your file and then call main()
at the bottom. E.g.
def main():
print 'doing stuff'
foo()
bar()
def foo():
print 'inside foo'
def bar():
print 'inside bar'
if __name__ == '__main__':
main()
if if __name__ == '__main__':
part ensures that main()
won't be called if the file is imported into another python program, but is only called when the file is run directly.
Of course, "main" doesn't mean anything... (__main__
does, however!) It's a psuedo-convention, but you could just as well call it do_stuff
, and then have if __name__ == '__main__': do_stuff()
at the bottom.
Edit: You might also want to see Guido's advice on writing main
's. Also, Daenyth makes an excellent point (and beat me to answering): The reason why you should do something like this isn't that is "standard" or even that it allows you to define functions below your "main" code. The reason you should do it is that it encourages you to write modular and reusable code.
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