Skip to main content

Posts

Showing posts with the label __main__

if __name__ == "__main__" in Python

  Learning Sections          show if __name__ == "__main__" in Python The if __name__ == "__main__" construct in Python is used to determine whether the Python script is being run as the main program or being imported as a module into another script. This is particularly useful for writing code that can be both imported and executed standalone. 1. Usage The common usage of if __name__ == "__main__" is: if __name__ == "__main__" : # Code to be executed when the script is run directly 2. Example Consider the following example: # Module code def hello (): print ( "Hello, world!" ) if __name__ == "__main__" : # Executed when the script is run directly hello () If you run this script directly, it will print Hello, world! . However, if you import this script as a module into another script, the hello() function will not be executed unless exp...