icon: LiWrench
Writing & Running Python Scripts
A Python script is a file containing Python code that is intended to be directly executed.
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. ✦ 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.
✦ Open up your Visual Studio Code
✦ Let's create a simple script that prints "Hello, World!".
hello_world
. Note that Python Scripts must have the .py
extension. 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.
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.
All import statements should be at the top of the file.
import os
import sys
import requests
Define global variables after the import statements. These are variables that are meant to be used throughout the script.
MEASUREMENT_UNIT = "cm"
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
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}")
if __name__ == "__main__":
Statementif __name__ == "__main__":
statement to check whether the script is being run directly or imported as a module. True
, and you can call the main()
function or any other code you want to execute.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()
#
) are crucial for making your code understandable to others and your future self.snake_case
for variable and function names.try
and except
blocks to handle potential errors in your scripts.