0

$USD

$USD
TUTORIALS Raspberry Pi

Raspberry Pi 3 Raspbian: Running Python from the command line

DFRobot Apr 27 2018 1257

In this tutorial we will check how to print a very simple “Hello World” message with Python running on the command line, on the Raspberry Pi. If you want to learn how to print a “Hello World” message using IDLE, the Python IDE, please check this previous article.


As mentioned in the previous tutorial, some versions of the Raspbian operating system have two versions of Python installed (Python 2.x and Python 3.x, where x is the minor version). You can check more about Python versioning here.


For this tutorial, I’m running version 4.9 of Raspbian, installed using NOOBS, which includes both versions of Python.


So, we are going to check how to run the “Hello World” printing program from the command line in the two versions of Python.


In both cases, the first thing we will need to do is opening the corresponding Python interpreter and then sending the command to print the message.


This tutorial was tested on a Raspberry Pi 3 model B+.


Running on Python 2.x


As mentioned, we will need to open the Python interpreter to get started. To do it, simply open a command line and type the following command:

python
After sending the command, it should start the interpreter, a shown in figure 1. Note that, as highlighted, the interpreter lists the whole Python version, including the minor and the micro version.



Figure 1 – Starting the Python 2.x interpreter via command line.

Now to print a “Hello World” message, simply type the following command and hit enter (you can change the string inside the double quotes to print whatever message you want):

print("Hello World!")

The message should get printed as illustrated in figure 2.



Figure 2 – Python 2.x “Hello World” program.

You can keep exploring other Python commands in the prompt. When you finish, simply close the whole command line.


Running on Python 3.x


As we have seen in the previous section, if we just write the python command on the command line, it will open the Python 2.x interpreter. So, to open the Python 3.x interpreter, our command needs to reflect that.

After opening a new command line, simply type the following command and hit enter (notice the 3 at the end of the command):

python3
As shown in figure 3, now it will open the Python 3 interpreter. You can confirm that by the version highlighted in the figure.



Figure 3 – Starting the Python 3.x interpreter via command line.

To print the “Hello World” message, simply send the same Python command we have used before.

print("Hello World!")
You should get the same result, as illustrated in figure 4.



Figure 4 – Python 3.x “Hello World” program.