Python Scripts

What is a Python Script?

A Python script is a plain text file containing Python code that is executed from top to bottom. Scripts are used to automate tasks, run programs, or perform computations.

Characteristics of Python Scripts

Example 1: Simple Script

print("This script prints a greeting message.")

Example 2: Script with Functions

def greet(name):
    print(f"Hello, {name}!")

greet("John")

Example 3: Script with Main Guard

def main():
    print("Script is running as main program")

if __name__ == "__main__":
    main()

Running a Python Script

To run a script, use the command line:

python script_name.py

Why Use the Main Guard?

The if __name__ == "__main__": guard ensures that certain code only runs when the script is executed directly, not when imported as a module. This improves code reuse and modularity.