Python Tutorial (7) - Interpreter

Time: Column:Python views:292

Installing and Running Python 3 on Linux/Unix and Windows

On Linux/Unix systems, the default Python version is typically 2.x. However, you can install Python 3.x in the /usr/local/python3 directory.

After installation, you can add the path /usr/local/python3/bin to your Linux/Unix system's environment variables, allowing you to start Python 3 by typing the following command in the shell terminal:

$ PATH=$PATH:/usr/local/python3/bin/python3    # Set environment variable
$ python3 --version
Python 3.4.0


On Windows, you can set the Python environment variable with the following command, assuming your Python installation is located in C:Python34:

set path=%path%;C:python34


Interactive Programming

You can start the Python interpreter by typing the "Python" command in the terminal:

$ python3


After executing the above command, you'll see the following window:

$ python3
Python 3.4.0 (default, Apr 11 2014, 13:05:11)
[GCC 4.8.2] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>>


Now, enter the following statement at the Python prompt and press Enter to see the result:

print("Hello, Python!")


The output will be:

Hello, Python!


When entering multi-line statements, continuation is necessary. Let's look at the following if statement:

>>> flag = True
>>> if flag:
...     print("The flag condition is True!")
...
The flag condition is True!



Script Programming

Copy the following code into a file named hello.py:

print("Hello, Python!")


Execute the script with the following command:

python3 hello.py


The output will be:

Hello, Python!


On Linux/Unix systems, you can make the Python script executable like a shell script by adding the following line at the top of the script:

#! /usr/bin/env python3


Then, modify the script's permissions to make it executable with the following command:

$ chmod +x hello.py


Now, run the script with:

./hello.py


The output will be:

Hello, Python!