The main block, explained
Since part 4, the starter code of function tasks has ended with a block like this:
if __name__ == "__main__":
print(mean([1, 2, 3]))
Now that you write modules of your own, you can see what it does and why it's there.
Importing runs the module
When Python imports a module, it runs the module's file from top to bottom. A def only defines a function, but any other code at the top level of the file runs too. So test prints left in a module show up in every program that imports it:
import tools
print("The main program starts")
print(tools.shout("hello"))def shout(text):
return text.upper() + "!"
print("Testing shout:", shout("test"))Testing shout: TEST!
The main program starts
HELLO!The first line isn't the main program's at all: it's the module's own test, run by the import.
The variable name
Python gives every module a variable called __name__. In the file Python started, the program itself, its value is "__main__". In a module that was imported, it's the module's name:
import tools
print("In main.py, __name__ is", __name__)print("In tools.py, __name__ is", __name__)In tools.py, __name__ is tools
In main.py, __name__ is __main__The main block
So if __name__ == "__main__": means "only when this file is the program that was started". Put a module's tests under it, and they run when you run the module's file itself, but stay quiet when another program imports it:
import tools
print(tools.shout("hello"))def shout(text):
return text.upper() + "!"
if __name__ == "__main__":
print("Testing shout:", shout("test"))HELLO!The block is called the main block. It's a convention, not a rule of the language, but nearly every Python module that has code to test or run uses it.
And the checks on this site
The checks for function tasks do exactly what import does: they load your program as a module, so its __name__ isn't "__main__" and the main block is skipped. Then they call your functions themselves. That's why your own test calls belong in the main block: there they help you while you write the function, and they don't get mixed into what the checks see. A test print outside the block would run at every check.