Writing & Running Python Scripts

What is Python Script

A Python script is a file containing Python code that is intended to be directly executed.

  • ✦ Unlike Jupyter Notebooks, which allow for an interactive coding experience with immediate feedback for each cell, Python scripts are run from start to finish by the Python interpreter.
  • ✦ Scripts are ideal for projects and tasks that require automation or when deploying applications.



Checking Python Installation

  • ✦ This is a quick way to check if your Python has been installed correctly

  • ✦ Open your terminal (Command Prompt on Windows, Terminal on macOS and Linux) and type:

    • python --version
  • ✦ This command should return the version of Python installed.




Writing Python Script

"Hello World" Script

  • ✦ Open up your Visual Studio Code

    • Choose a folder where you want to save your project
  • ✦ Let's create a simple script that prints "Hello, World!".

    • Click on the "New File"
    • Give the file a name. Here, we use hello_world. Note that Python Scripts must have the .py extension.
    • Write the following code in the editor and run it
      • print("Hello, World!")
  • ✦ If you can see the output "Hello World" being printed out in the "Terminal", that's good news. That means that your Visual Studio and Python are configured properly and you're good to start with writing your python code.




Structure of a Python Script

A well-structured Python script not only makes your code more readable and maintainable but also adheres to the conventions that Python developers expect. This section will guide you through the essential components and good practices for structuring your Python scripts.

1. Import Statements

All import statements should be at the top of the file.

  • ✦ This convention makes it clear which modules the script depends on, facilitating maintenance and avoiding unexpected errors due to late imports.
  • ✦ Standard library imports should be grouped together, followed by third-party imports, and then any local module imports, each group separated by a blank line.
import os 
import sys 
import requests

2. Global Variables

Define global variables after the import statements. These are variables that are meant to be used throughout the script.

MEASUREMENT_UNIT = "cm"

 3. Function and Class Definitions

Next, define your functions and classes. Each should have a descriptive docstring (see the first line of string enclosed in triple quotes) explaining what it does. Keep related functions and classes close to each other in the code.

def calculate_area(length, width):
    """Calculate and return the area of a rectangle."""
    return length * width

 4. Main Function

It's a good practice to encapsulate the script's main functionality in a function, often named main(). This function will be called when the script is executed directly.

def main():
    """Main function of the script."""
    length = float(input("Enter the length: "))
    width = float(input("Enter the width: "))
    area = calculate_area(length, width)
    print(f"The area of the rectangle is: {area} {MEASUREMENT_UNIT}")

5. if __name__ == "__main__": Statement

  • ✦ At the bottom of the script, use the if __name__ == "__main__": statement to check whether the script is being run directly or imported as a module.
  • If the script is run directly, this condition is True, and you can call the main() function or any other code you want to execute.
  • ✦ This practice not only makes your script executable as a standalone program but also allows its functions and classes to be imported into other scripts without executing the main code block.
if __name__ == "__main__": 
	# if the script is run directly 
	# e.g. python myscript.py
	# Then the main() function will be called
	main()

This is how the complete script looks like:

import os 
import sys 
import requests


MEASUREMENT_UNIT = "cm"

def calculate_area(length, width):
    """Calculate and return the area of a rectangle."""
    return length * width


def main():
    """Main function of the script."""
    length = float(input("Enter the length in cm: "))
    width = float(input("Enter the width in cm: "))
    area = calculate_area(length, width)
    print(f"The area of the rectangle is: {area} {MEASUREMENT_UNIT}")

if __name__ == "__main__": 
	main()



Some Good Practice for Scripts

  • Use Comments:
    • Comments (#) are crucial for making your code understandable to others and your future self.
  • Follow Naming Conventions:
    • Use meaningful variable and function names. Python convention is to use snake_case for variable and function names.
  • Modularize Your Code:
    • Break your code into functions or modules for better readability and reusability.
  • Error Handling:



# [Extra] Further Readings