Running a Python script means executing a Python program so the computer can read the instructions and display the output. After installing Python and setting up your IDE, the next important step is learning how to properly run your Python files.
A Python script is a file that contains Python code and is saved with the extension .py. For example, a file named program.py is a Python script.
CREATING A PYTHON SCRIPT
To create a Python script, follow these steps:
Step 1
Open your IDE or code editor.
Step 2
Click on New File.
Step 3
Write your Python code. Example:
print(“Hello World”)
Step 4
Save the file with a .py extension such as hello.py.
RUNNING PYTHON SCRIPTS USING COMMAND PROMPT
You can run a Python script using Command Prompt in Windows or Terminal in Mac or Linux.
Step 1
Open Command Prompt or Terminal.
Step 2
Navigate to the folder where your Python file is saved using the cd command.
Step 3
Type the following command:
python filename.py
Example:
python hello.py
If everything is correct, the output will be displayed on the screen.
RUNNING PYTHON SCRIPTS USING AN IDE
Most IDEs allow you to run scripts easily with a Run button.
IDLE
Open the file, click Run, then select Run Module.
Visual Studio Code
Open the file and click the Run button or press Ctrl + F5.
PyCharm
Open the file and click the Run icon at the top.
The output will appear in the terminal or output panel inside the IDE.
COMMON ERRORS WHILE RUNNING SCRIPTS
File Not Found Error
This happens when you are not in the correct folder while running the script.
Python Not Recognized Error
This occurs if Python was not added to PATH during installation.
Syntax Error
This occurs when there is a mistake in your code such as missing quotation marks or brackets.
WHY RUNNING SCRIPTS IS IMPORTANT
Running Python scripts allows you to test your code, identify errors, and see the results of your logic. It is a fundamental skill every Python learner must practice.
Once you understand how to run Python scripts, you can confidently build programs and explore more advanced Python concepts.