How to Run a Python Script?

python script

Python scripting is the most fundamental thing you’ll have to learn to call yourself a Python programmer. With the use of Python scripts you can get things done automatically and make meaningful decisions by analyzing raw data.

You’ll have to run your code to understand if it works. If you face any errors, you can debug them or write more code to get things done. So, if you’re a beginner struggling with Python scripting, this guide is for you.

In this guide, we’ll walk you through the essentials of running a Python script with the .py extension, from understanding the basics of Python scripting to executing your code flawlessly on any compatible device.

Let’s dive in.

What Is A Python Script?

Python scripts automate tasks, analyze data, and build applications. Here’s a breakdown of what is python scripting:

  • Code File Format: Python scripts are saved in a .py format, distinguishing them as files containing Python code.
  • Executable Instructions: Within these files, you’ll find sequences of Python instructions written in a human-readable format.
  • Versatility: Python scripts are incredibly versatile and can perform various tasks, from simple calculations to complex data analysis and web development.
  • Platform Independence: Once written, Python scripts can be executed on any device with Python installed, irrespective of the underlying operating system.

Additionally, on Windows 10 systems, Python scripts can also have the “.pyw” extension, helping to run scripts in a more GUI-friendly manner.

Different Approaches To Executing A Python Script

Python scripts can be executed using a variety of methods. Here are some commonly employed approaches:

  • Interactive Mode
  • Command Line Execution
  • Utilizing a Text Editor like VS Code
  • Integrated Development Environment (IDE) such as PyCharm

How To Run A Python Script?

Running a Python script involves a simple process, which we can better understand by examining a simple Python scripting tutorial.

But before that, you must install Python on your system. To confirm whether Python is installed on your system, open the Command Prompt (on Windows) and type:

python -V

This command will either provide the version number of the installed Python interpreter or show the following error if not found.

Now let’s consider an example script to calculate the sum of two numbers:

num1 = 5
num2 = 3
sum = num1 + num2
print("The sum is:", sum)

Output

The sum is: 8

Once it’s saved with the “.py” extension, indicating it’s a Python code file, you can execute the script using any Python interpreter. 

In this example, we demonstrated this process by calculating the sum of two numbers assigned to variables num1 and num2 using the addition operator. You can print the result using the print() function. 

Learners Tip
It’s worth noting that Python scripts follow the same syntax rules as any other Python code, eliminating the need for semicolons at the end of statements and any imports to execute basic scripts. 

Get a detailed understanding of Python File Open with our comprehensive guide: “Python File Open: How to Open a File in Python?

Different Approaches To Executing A Python Script

You can use a variety of methods to run a Python script. Here are some commonly employed approaches to Python scripting:

  • Interactive Mode
  • Command Line Execution
  • Utilizing a Text Editor like VS Code
  • Integrated Development Environment (IDE) such as PyCharm

How To Run Python Script In Interactive Mode?

Interactive mode in Python allows you to execute Python commands and see their results immediately. 

It makes it easier to experiment with Python code, test small snippets, or quickly perform calculations without creating and executing a separate script file. 

The Windows way

You can enter interactive mode by typing Python in your terminal or command prompt without specifying a script file. Once in interactive mode, you’ll see a prompt (usually >>>) where you can type Python commands.

Example 1: Using Print Function In Interactive Mode

>>> print("Welcome to Interactive Python Mode!")

Output

Welcome to Interactive Python Mode!

Explanation
In this Python script example, we use the print() function to display the message “Welcome to Interactive Python Mode!” in the interactive mode. When you press enter after typing the command, Python immediately executes it and displays the output. Interactive mode allows for quick testing and execution of Python commands without saving them in a script file.

The MAC way

Steps to run Python script in interactive mode in MAC OS:

  1. Press Cmd + Space to open Spotlight search and type “Terminal” to enter the terminal.
  2. Navigate to the script file using the cd command
  3. To run the Python script, use the code – exec(open(‘script_name.py’).read())
  4. Once the script successfully runs, you’ll be able to call all the functions defined in the script directly
  5. To exit from the interactive mode, type exit()

Example 2: Using Interactive Execution

>>> x = 10
>>> y = 20
>>> x + y

OUTPUT

30

Explanation
In this example, we perform a simple calculation by assigning values to variables x and y and then adding them together. Python immediately evaluates the expression x + y and returns the result 30. This demonstrates how interactive mode can be used for quick calculations and experimentation with Python expressions.

The Linux way

Steps to run Python script in interactive mode in Linux:

  1. Press Ctrl + Alt + T to open the terminal window
  2. Use the cd command to reach the script’s destination
  3. Now, use the code below to run the script- python3 -i script_name.py
  4. Use quit() to exit the interactive mode

Example 3: Interactive Mode Comparison With Advanced Maths

>>> import math
>>> radius = 5
>>> circumference = 2 * math.pi * radius
>>> circumference

Output

31.41592653589793

Explanation
We import the math module to access mathematical functions and constants in this example. Then, we define a variable radius with a value of 5. Using the formula for calculating the circumference of a circle (2 * pi * radius), we calculate the circumference and store the result in the variable circumference. 

Python immediately evaluates the expression by typing circumference and displays the calculated value, approximately 31.42. This demonstrates how interactive mode allows for exploring more complex mathematical computations in real time without requiring a script file.

Learners Tip
To terminate interactive mode, use the key combination ‘Ctrl+Z‘ followed by pressing ‘Enter’ or typing ‘exit()‘ and then pressing ‘Enter

Join the ranks of successful coders by mastering the Python basics with our course on “Python Fundamentals for Beginners.

How To Run Python Script by The Command Line

The command line, also known as the terminal or command prompt, provides a text-based interface for interacting with a computer’s operating system. 

It allows users to execute commands and run programs by typing text commands rather than using a graphical user interface. 

In running Python scripts, the command line provides a convenient way to execute Python code stored in script files (.py files) directly from the terminal or command prompt.

Be it Windows, Mac OS, or even Linux, we can execute any Python script from the command line by navigating to the file directory in the terminal and entering the command “python3 script_name.py.”

Example 1: Running A Python Script To Generate A Fibonacci Sequence

# Fibonacci sequence generator
def fibonacci(n):
    fib_sequence = [0, 1]
    for i in range(2, n):
        fib_sequence.append(fib_sequence[i-1] + fib_sequence[i-2])
    return fib_sequence

# Generate Fibonacci sequence up to 10 numbers
print(fibonacci(10))

OUTPUT

[0, 1, 1, 2, 3, 5, 8, 13, 21, 34]

Explanation
In this example, we have a Python script saved as fibonacci.py, which generates the Fibonacci sequence up to a specified number of terms. We execute this script from the command line by navigating to the directory containing the script and typing python fibonacci.py. 

The script calculates the Fibonacci sequence up to 10 numbers and prints the result [0, 1, 1, 2, 3, 5, 8, 13, 21, 34], demonstrating the execution of Python code from the command line.

Example 2: Running A Python Script To Generate A Password

import random

# Function to generate a random password
def generate_password(length=8):
    characters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%^&*()-_"
    password = ''.join(random.choice(characters) for _ in range(length))
    return password

# Generate a random password of length 12
print("Generated Password:", generate_password(12))

OUTPUT

Generated Password: Jm&5F@kS-8r$

Explanation
In this example, we have a Python script saved as generate_password.py that generates a random password of specified length using a combination of letters, digits, and special characters. 

We execute this script from the command line by navigating to the directory containing the script and typing python generate_password.py

The script generates a random password of length 12 and prints it to the console, demonstrating how Python scripts can be used to perform tasks like password generation from the command line.

Finding it difficult to code efficiently in Python? Check out “Python Cheat Sheet” for quick tips!

How To Run Python Script by Utilizing a Text Editor like VS Code

The steps to run a Python script using a text editor like VS Code are mostly the same in Windows, MAC, and Linux. To perform Python scripting with VS Code, you typically follow these steps:

  • Open VS Code and navigate to the directory containing your Python script.
  • Open the script file in VS Code by clicking on it.
  • Ensure that you have the Python extension installed in VS Code.
  • Optionally, create a virtual environment for your project to manage dependencies.
  • Use the terminal within VS Code to navigate to the directory containing your script.
  • Run the Python script by typing python script_name.py in the terminal and pressing Enter.

Example 1: Python Script For Text Analysis

# Analyze text
text = "The quick brown fox jumps over the lazy dog"
words = text.split()
word_count = len(words)
print("Word count:", word_count)

OUTPUT

Word count: 9

Explanation
In this example, we have a Python script saved as text_analysis.py that analyzes a given text by counting the number of words. We open the script file in VS Code, navigate to the directory containing it, and run the script by typing python text_analysis.py in the integrated terminal. 

The script splits the text into words, counts the number of words, and prints the result to the terminal, demonstrating how Python scripts can be executed within VS Code.

Example 2: Python Script For Web Scraping

import requests
from bs4 import BeautifulSoup

# Define URL to scrape
url = 'https://en.wikipedia.org/wiki/Python_(programming_language)'

# Send a GET request to the URL
response = requests.get(url)

# Parse HTML content
soup = BeautifulSoup(response.content, 'html.parser')

# Find and print the title of the page
title = soup.find('h1', {'id': 'firstHeading'}).text
print("Title:", title)

OUTPUT

Title: Python (programming language)

In this Python scripting example, we have a script saved as web_scraping.py that performs web scraping to extract information about the Python programming language from a Wikipedia page. 

We open the script file in VS Code, navigate to the directory containing it, and run the script by typing python web_scraping.py in the integrated terminal. 

The script sends a GET request to the specified URL, parses the HTML content using BeautifulSoup, and extracts the page title, which is then printed to the terminal. 

This demonstrates how Python scripting can be used for web scraping tasks within VS Code, allowing developers to extract data from websites for various purposes.

Explore ‘Top 10 Uses of Python in Real World with Examples‘ for Hands-on experience

Python Scripts Using Integrated Development Environment (IDE) such as PyCharm

Integrated Development Environments (IDEs) like PyCharm provide a comprehensive environment for Python development, offering features such as code editing, debugging, and version control. 

PyCharm simplifies the process of writing and executing Python scripts by providing a user-friendly interface and built-in tools to manage projects efficiently.

Steps to Run Python Scripts Using PyCharm:

  • Open PyCharm and create or open a Python project.
  • In the project explorer, navigate to the directory where your Python script is located.
  • Right-click on the script file and select “Run <script_name>.py” from the context menu.
  • Alternatively, you can open the script file, navigate to the toolbar, and click the green “Run” button to execute the script.
  • PyCharm will run the script and display the output in the Run tool window.

Example: Python Script for Generating Random Quotes

import random

# List of random quotes
quotes = [
    "The only way to do great work is to love what you do. - Steve Jobs",
    "Innovation distinguishes between a leader and a follower. - Steve Jobs",
    "Stay hungry, stay foolish. - Steve Jobs",
    "Your time is limited, don't waste it living someone else's life. - Steve Jobs",
    "I have not failed. I've just found 10,000 ways that won't work. - Thomas Edison"
]

# Select and print a random quote
random_quote = random.choice(quotes)
print("Random Quote:", random_quote)

OUTPUT

Random Quote: Stay hungry, stay foolish. - Steve Jobs

Explanation
In this Python script example, we have a Python script saved as random_quote_generator.py that selects and prints a random quote from a list of famous quotes. We open PyCharm, create a new Python project or open an existing one, and add the script file to the project. 

Then, we run the script by right-clicking on the file in the project explorer and selecting “Run <script_name>.py” PyCharm executes the script and displays the chosen randomly quote in the Run tool window, showcasing how Python scripts can be run seamlessly within an IDE like PyCharm for various tasks.

We’ve discussed four distinct approaches for executing Python scripts on your device. Any of the above methods can be employed depending on your device’s specifications and preferences.

Strengthen your understanding of PyCharm with our PyCharm Tutorial for Beginners

Converting The Python Script Into A .Exe File

To convert a Python script into a standalone executable (.exe) file, you can use tools like PyInstaller or cx_Freeze. 

These tools package your Python script and the interpreter into a single executable file that can be run on any Windows machine without requiring Python to be installed. 

Here’s a general overview of the process using PyInstaller:

  1. Install PyInstaller: First, ensure you have PyInstaller installed. You can install it via pip by running:
pip install pyinstaller
  1. Navigate to Your Script’s Directory: Open a command prompt or terminal window and navigate to your Python script’s directory.
  1. Create the Executable: Run the following command to create the executable:
pyinstaller --onefile your_script.py

Replace ‘your_script.py’ with the name of your Python script.

  1. Locate The Executable: Once PyInstaller finishes creating the executable, you can find it in the dist directory within your script’s directory.
  1. Test The Executable: You can run the generated .exe file on any Windows machine without installing Python. Double-click the .exe file to execute your Python script.

Also read- “Top 30 Python Libraries To Know” to discover essential libraries for your Python projects!

Wrapping Up

Running a Python script is a fundamental skill that opens doors to countless opportunities in software development, data analysis, and automation. 

Whether you’re a beginner or an experienced programmer, mastering Python scripting enhances your capabilities and empowers you to bring your ideas to life. 

Additionally, Great Learning offers free Python courses tailored to different skill levels for those seeking to deepen their Python expertise, providing accessible pathways for continuous learning and growth. 

Moreover, for those aspiring to excel in data science and business analytics, Great Learning’s PG Program in Data Science & Business Analytics equips learners with in-depth knowledge and practical skills, paving the way for successful careers in the dynamic field of data-driven decision-making. 

With these resources at your disposal, the journey of Python scripting becomes not only fulfilling but also transformative, propelling you towards greater achievements in the realm of technology and analytics.

Frequently Asked Questions

How can I optimize the performance of my Python scripts?

Several ways to optimize the performance of Python scripts include using efficient data structures and algorithms, minimizing unnecessary computations, utilizing libraries like NumPy for numerical operations, and implementing concurrency or parallelism using threads or processes.

Are there any best practices for structuring large Python projects with multiple scripts and modules?

Yes, best practices for structuring large Python projects include:

Organizing code into modules and packages based on functionality
Adhering to naming conventions
Implementing clear documentation and comments
Utilizing version control systems like Git for collaboration and code management

Additionally, virtual environments should be considered to manage dependencies and ensure project isolation.

What are the best practices for handling exceptions in Python scripts?

Best practices for exception handling in Python scripts include:

Using try-except blocks to catch and handle specific exceptions
Logging errors for debugging purposes
Raising custom exceptions when necessary

It’s also recommended that exceptions are handled gracefully to prevent crashes and maintain the stability of your scripts.

Can I distribute my Python scripts as standalone applications for users who don’t have Python installed?

You can convert your Python scripts into standalone executable files (.exe) using tools like PyInstaller or cx_Freeze. These tools package your script and the Python interpreter into a single executable file that can be run on machines without Python installed, providing a convenient way to distribute your applications to users.

→ Explore this Curated Program for You ←

Avatar photo
Great Learning Editorial Team
The Great Learning Editorial Staff includes a dynamic team of subject matter experts, instructors, and education professionals who combine their deep industry knowledge with innovative teaching methods. Their mission is to provide learners with the skills and insights needed to excel in their careers, whether through upskilling, reskilling, or transitioning into new fields.

Full Stack Software Development Course from UT Austin

Learn full-stack development and build modern web applications through hands-on projects. Earn a certificate from UT Austin to enhance your career in tech.

4.8 ★ Ratings

Course Duration : 28 Weeks

Cloud Computing PG Program by Great Lakes

Enroll in India's top-rated Cloud Program for comprehensive learning. Earn a prestigious certificate and become proficient in 120+ cloud services. Access live mentorship and dedicated career support.

4.62 ★ (2,760 Ratings)

Course Duration : 8 months

Scroll to Top