Write your first python program
print("Hello World!")
name = input("What is your name? ")
print("Nice to meet you,", name)
Write your first function in python
def main():
print("Hello World!")
name = input("What is your name? ")
print("Nice to meet you,", name)
if __name__ == "__main__":
main()
Python doesn't automatically look for a function named main
when the program starts. So we need to write this condition
if __name__ == "__main__":
main()
Why do we need to do this?
Because in Python you might be executing your code as a program, but you might also be including this code as a module in another program. And if this was executed from the terminal or the command line, then you want the main function to be called.
Now, if the code was included as a module in another program, then you wouldn't want all my code just to start running when it was imported into the other program, because that would cause problems.
So these two lines help distinguish between when a Python file is being included in another program, or when that Python code is being executed as its own program.
Top comments (0)