DEV Community

Ahmed Gouda
Ahmed Gouda

Posted on • Edited on • Originally published at ahmedgouda.hashnode.dev

Write Your First Python Program

Write your first python program

print("Hello World!")
name = input("What is your name? ")
print("Nice to meet you,", name)
Enter fullscreen mode Exit fullscreen mode

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()
Enter fullscreen mode Exit fullscreen mode

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()
Enter fullscreen mode Exit fullscreen mode
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)