We are going to be writing our first program through the Python interactive shell. Before we begin, ensure that you have Python installed on your machine.
To check whether Python is installed properly, perform the following steps:
Open the command prompt.
Type in the command python and press Enter. This should open the Python interpreter, and you should see a message containing the Python version you installed.
Observe the output. It should be similar to what's shown in the following screenshot:
Once the interactive shell opens, on the first line, you should see the Python version information. This includes its major version and the release date. As you can see from the preceding screenshot, it shows us that we're using Python 3, minor version 6, which was released on December 19, 2017. We can also see information on the system the interactive shell is running on. On the second line, we can see a few examples of commands we can write, and finally the prompt to enter a command >>> on the third line.
The Python interactive shell can be thought of as just any other shell that interfaces with the operating system (for example, Bash or CMD), but in this case, it interfaces with the Python interpreter. Through it, we can execute Python instructions. It presents a command-line interface.
In this exercise, we will learn how to work with the Python interpreter:
At the command prompt, enter the following command to run the popular Hello World! program:
>>> print("Hello World!") Hello World >>>
Calling print logs the passed message to the standard output.
Anything you type into the shell is echoed back. Type "Echo" in the shell to check this:
>>> "Echo" 'Echo' >>> 1234 1234 >>>
You can even do some calculations (note that the order of operations is observed). Carry out a few mathematical operations in the terminal, like this:
>>> 9 + 3 12 >>> 100 * 5 20 >>> -6 + 5 * 3 9 >>>
Exit the shell by running the exit command:
>>> exit
When you exit the Python interactive shell and relaunch it, you will notice that any variables you had defined or commands you had run in the previous session are gone. Therefore, we can't reuse them. Another way to run a Python program is by running code that has been saved in a file. This allows us to run many instructions at a time and also reuse them, as we'll see later on in the book. In the next section, we'll take a look at how to do this.
In this activity, we will perform some basic operations using the Python interactive shell.
The steps are as follows:
Open the terminal.
Open the interactive shell.
Print Happy birthday or any message to the standard output.
Run the operation 17 + 35 * 2. The result should be 87.
Print the numbers 1 to 9 on a single row.
Exit the shell.