This question already has an answer here:
I am writing a simple Python program with some functions, one of which is a main()
function executes the other functions. However when I run the code below there is no output. Can someone tell me if they see an error in the structure?
def print1():
print("this is also a function")
def print2():
print("this is a function")
def main():
print1()
print2()
You need to call
main()
. Right now it is just a definition. What use is an entry in a dictionary if nobody uses the word?It is common in Python programs to do things differently depending on if the file is being imported or run. When a file is executed, the
__name__
variable is set either to'__main__'
or the name of the file. It is set to'__main__'
if the file is being executed as a python script, and it is set to the name of the file if it is being imported. You can use this information so that you don't actually run anything if it is just being imported instead of being run as a python script:That way, you can import the module, and use the functions without
main()
being called. If it is run as a python script, however,main()
will be called.I believe what you mean to be doing is
Call this script something.py and then run
python something.py
from your command line.You need to call
main()
in order for it to run.Add this to the bottom of your code.
See https://docs.python.org/2/library/main.html
Main needs to be called explicitly. You can do it without the if statement, but this allows your code to be either a module or a main program. If it is imported as a module, main() won't be called. If it is the main program then it will be called.
You are thinking like a C programmer. In this case python acts more like a shell script. Anything not in a function or class definition will be executed.