Altcademy - a Forbes magazine logo Best Coding Bootcamp 2023

How to run Python script in linux

Introduction

If you're new to programming, you might have heard about Python, an easy-to-learn and versatile programming language. It is widely used in various fields such as web development, data analysis, artificial intelligence, and more. In this blog, we'll learn how to run a Python script in Linux, a popular open-source operating system.

Don't worry if you're not familiar with some of the terms or concepts mentioned above. In this blog, we'll break down everything step by step, providing explanations, analogies, and code examples to make it easy for you to understand.

What is a Python script?

Before we dive into running a Python script in Linux, let's first understand what a Python script is. A Python script is a collection of Python code saved in a text file with a ".py" file extension. These scripts are designed to execute a specific task or a series of tasks.

For example, you can write a script that reads data from a text file, processes the data, and then saves the results in another file. Think of a Python script as a recipe, detailing the steps and ingredients required to complete a dish.

Setting up Python on Linux

To run a Python script on a Linux system, you must first have Python installed. Most Linux distributions come with Python pre-installed. To check if you have Python installed, open the terminal and type:

python --version

If Python is installed, you should see the version number. If not, you can install it using your distribution's package manager. For example, on Ubuntu or Debian-based systems, you can use the following command:

sudo apt-get install python3

For Fedora, CentOS, or RHEL-based systems, use:

sudo yum install python3

Once Python is installed, you can start writing and running Python scripts.

Writing your first Python script

To write a Python script, you can use any text editor that you're comfortable with, such as Vim, Nano, or Gedit. For this tutorial, let's use Gedit, which is a user-friendly text editor available on most Linux distributions.

To create a new Python script, open the terminal and type:

gedit hello.py

This will open a new blank file called hello.py in Gedit. In this file, type the following code:

print("Hello, World!")

This simple script contains a single line of Python code that uses the print function to display the text "Hello, World!" on the screen. Save the file and close Gedit.

Running your Python script

Now that you've written your first Python script, it's time to run it. In the terminal, navigate to the directory containing your hello.py script using the cd command. For example, if your script is located in the Documents folder, type:

cd Documents

To run your Python script, type the following command:

python3 hello.py

This command tells the Python interpreter (the program responsible for executing Python code) to read and execute the code in your hello.py script. You should see the following output:

Hello, World!

Congratulations! You've just run your first Python script in Linux.

Using variables and user input

Python scripts can be much more than just printing text. You can use variables to store and manipulate data, and even get input from users. Let's create another Python script that asks for the user's name and greets them by name.

Open a new Gedit window and create a new Python script called greet.py. Type the following code:

name = input("What is your name? ")
print(f"Hello, {name}!")

In this script, we use the input function to get the user's name. The input function displays a prompt (in this case, "What is your name? ") and waits for the user to enter some text. Once the user presses Enter, the text they entered is stored in the name variable.

The second line of the script uses the print function again, but this time, we're using an f-string (formatted string literal) to insert the user's name into the text. Save the file and run the script in the terminal:

python3 greet.py

You'll be prompted to enter your name. After you do so, the script will greet you by name:

What is your name? Alice
Hello, Alice!

Creating a simple calculator

Now that you've learned about variables and user input, let's create a more complex script—a simple calculator that can add, subtract, multiply, and divide two numbers.

Create a new Python script called calculator.py and type the following code:

# Get input from the user
num1 = float(input("Enter the first number: "))
num2 = float(input("Enter the second number: "))
operation = input("Choose an operation (+, -, *, /): ")

# Perform the selected operation
if operation == "+":
    result = num1 + num2
elif operation == "-":
    result = num1 - num2
elif operation == "*":
    result = num1 * num2
elif operation == "/":
    result = num1 / num2
else:
    print("Invalid operation")
    exit()

# Display the result
print(f"The result is: {result}")

This script first prompts the user to enter two numbers and an operation. The float function converts the user's input into a floating-point number (a number that can have decimal places).

Next, the script uses an if-elif-else statement to determine which operation to perform based on the user's input. If the user entered an invalid operation, the script displays an error message and exits.

Finally, the script displays the result of the operation. Save the file and run the script in the terminal:

python3 calculator.py

Enter two numbers and an operation when prompted, and the script will display the result:

Enter the first number: 10
Enter the second number: 5
Choose an operation (+, -, *, /): *
The result is: 50.0

Final thoughts

In this blog, we've learned how to run Python scripts in Linux, starting with installing Python, writing and running simple Python scripts, and creating a basic calculator. The examples provided in this tutorial are just the tip of the iceberg when it comes to Python's capabilities.

As you continue learning programming, you'll discover more powerful features and libraries that Python has to offer, allowing you to create even more complex and useful scripts. Keep practicing and exploring, and you'll be amazed by what you can achieve with Python and Linux.