πHow to Run Python Scripts : Step-by-Step Guide
Running Python scripts can be done in multiple ways, including via the command line, integrated development environments (IDEs), or file managers. This guide explains each method in detail.
πWhat is a Script in Python?
A Python script is a file containing Python code with the .py extension. Scripts can be executed directly or imported as modules.
πHow to Run Python Code and Scripts Interactively
πSteps to Run Python Code in Interactive Mode:
- Open the command line in interactive mode.
- Type the following command to start Python:
bash
python
- Write your Python code directly in the command prompt and press Enter to execute.
πExample Code:
python
print(‘Hello World!’)
πOutput:
nginx
Hello World!
πHow to Run Python Script Files from Windows GUI
πSteps to Run Python Scripts via Command Prompt:
- Open the command prompt.
- Type python followed by the script file name (e.g., example.py).
- Ensure the script file is saved with the .py or .pyw extension.
πCommand:
bash
python example.py
πOutput:
nginx
Hello World!
πHow to Run Python Scripts from an IDE (e.g., PyCharm)
Steps to Run Python Code in PyCharm IDE:
- Open PyCharm and create a new project.
- Name the project, select the root folder, and create a new Python file.
- Add your Python code in the newly created file.
- Right-click the file and select βRun File in Python Console.β
πExample Code in PyCharm:
python
print(‘Hello World from PyCharm!’)
πOutput in PyCharm Console:
csharp
Hello World from PyCharm!
πHow to Run Python Scripts Using a File Manager
πSteps to Run Python Code Using File Manager:
- Open Notepad and write your Python code.
- Save the file with the .py or .pyw extension.
- Right-click the file and choose βOpen with Python.β
πCode Example:
python
print(‘Hello World from File Manager!’)
input(‘Press Enter to exit…’)
πHow to Run Python Scripts Using Command Line (with File Path)
πSteps to Run Python Code with File Path:
- Save your Python file as example.py.
- Copy the full file path.
- Open the command prompt and run the following command:
bash
python “C:/path/to/your/example.py”
πOutput:
vbnet
Hello World!
Press Enter to exit…
πHow to Run Python Scripts on Linux
πSteps to Run Python Scripts in Linux Terminal:
- Open the Linux terminal.
- Type the following command to start Python:
bash
python3
- Write and execute your Python code directly.
πExample Code:
python
a = 25
b = 50
if a > b:
print(“a is greater”)
else:
print(“b is greater”)
πOutput:
csharp
b is greater
Alternatively, you can run the saved Python script file using:
bash
python3 /path/to/your/script.py
πPython Code vs Module vs Script: Key Differences
Parameters | Code | Module | Script |
Definition | Series of instructions | Organized series of codes | A file containing organized logic |
Execution | Run directly in Python interpreter | Imported and executed | Executed via Python interpreter |