You could write your code in the main body of your Python file, but using functions and passing arguments to it will make your code easier to maintain and understand. Therefore I recommend that you always write every script with a function called "main".
Function definition starts with the "def" keyword, followed by the name of the new function ("main" in this case), followed by the list of parameters in parentheses (nothing in this case). The content or body of the function is then indented to the right. The function definintion ends when the indentation stops. In our case that is the empty row between the line with the 'return' statement and the line with the 'print("before")' statement.
#!/usr/bin/env python def main(): print("Hello World") return print("before") main() print("after")
This script will print "before" followed by "Hello World", followed by "after".
- Use a main function to avoid globals.
- Python uses indentation for blocks instead of curly braces, and it uses the colon to start a block