You can run Python code directly on a terminal as commands or save the code in a file with .py
extension and run the Python file.
Terminal
Running commands directly on a terminal is recommended when you want to run something simple.
Open the command line and type python3
python3
You should see something like this on your terminal indicating the version, in my case, Python 3.6.9, the operating system, I’m using Linux, and some basic commands to help you.
The
tells us we are in the Python console.>>>
Python 3.6.9 (default, Nov 7 2019, 10:44:02)
[GCC 8.3.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>>
Let’s test it by running our first program to perform basic math and add two numbers.
>>> 2 + 2
The output is:
4
To exit the Python console simply type exit()
.
>>> exit()
Running .py files
If you have a complex program, with many lines of code, the Python console is not indicated.
The alternative is simply to open a text editor, type the code, and save the file with a .py
extension.
Let’s do that, create a file called second_program.py
with the following content.
print('Second Program')
The print()
function prints a message on screen.
The message goes inside the parentheses with either single quotes or double quotes, both work the same.
To run the program, on your terminal do the following:
python3 second_program.py
The output is:
Second Program