Logo

Python : Writing and Running Simple Scripts

Nov 12, 2020

Python allows you to run your instructions from a saved file. A file containing Python instructions is called a module. A script is a module that can be run.

By convention, Python scripts should have the file extension .py. The filename should be a valid filename, as defined by your operating system.

Creating a Script

Step 1 : Open your text editor.

Step 2 : Create a file called test1.py and insert the following code

print("---------------------------------")

print("Hello " * 5)

print("---------------------------------")

Step 3 : Save it to your working directory.

Step 4 : Open your terminal, change into the directory where the file is saved, and run the following command: python test1.py

python test1.py

Passing User Arguments to Scripts

To make a script more dynamic, you can have the user provide arguments to it when calling it

Step 1 : Create a new file called test2.py. Then, add the following code

import sys

print("This argument was passed to the script:", sys.argv[1])

Step 2 : Save and run the script as usual, passing it an argument, as illustrated here

python test2.py foobar