Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

The main function - called

  • main
  • def

In this example I added 3 lines to the previous file. The line main() calls the main function. We sometimes also say "runs the function" or "invokes the function". In this context they mean the same.

The two print-statements are not necessary to call the function, I only added them so it will be easy to see the order of the operations that you can observe by looking at the output.

def main():
    print("Hello")
    print("World")

print("before")
main()
print("after")
before
Hello
World
after
  • Use a main function to avoid globals and better structure your code.
  • Python uses indentation for blocks instead of curly braces, and it uses the colon : to start a block.