简体   繁体   中英

Can you call the main function at the top in python like perl?

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

Could you please try:

def main():
    print('hello')

and then call it as main()

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()

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.

因此,您只能在更早定义它后才能使用该函数。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM