0

Does anyone know if there is a way to do this?

For example this perl code works, but python does not?

#!/usr/bin/perl5.18
main();

sub main {
    print 'hello\n';
    return;
}
#!/usr/bin/env python3.4
main()

def main():
    print('hello')
    return

Thanks

nwellnhof
  • 32,319
  • 7
  • 89
  • 113
xcobbyz
  • 13
  • 1
  • 3
    main is undefined until you hit the def line, in python you have to define the function before you call it – Padraic Cunningham Oct 03 '15 at 13:44
  • if you import it from other module/file, yes you can :) that's a joke, btw. python reads code from top to the end. in any case if interpreter finds a usage (evaluation, execution) of an undefined variable, function etc. it stops working with an error code. have a look up this thread: http://stackoverflow.com/questions/2985047/order-of-execution-and-style-of-coding-in-python – marmeladze Oct 03 '15 at 15:51

4 Answers4

0

Could you please try:

def main():
    print('hello')

and then call it as main()

astromath
  • 302
  • 1
  • 3
  • 13
0

You need to write definition of main before you call it:

def main():
    print('hello')
    return

if __name__ == "__main__": # Avoid running main function when this file is imported instead of run directly.
    main()
LouYu
  • 671
  • 1
  • 6
  • 14
  • Re "You need to write definition of main before you call it", No, calls can precede definitions. – ikegami Oct 05 '15 at 14:47
  • @ikegami You can write codes that call it before definitions, but you can't run those codes and really call the function before the function is assigned to its codes. – LouYu Oct 06 '15 at 01:14
0

You can't have a call to a function before the function is declared, except if the call is within another function. Workaround:

def top():
    main()

...

def main():
    print('hello')
    return

top()

Not sure why you'd want to do that. In either language. It's definitely error-prone in Perl.

ikegami
  • 367,544
  • 15
  • 269
  • 518
0

So, you can use the function only after defining it earlier.