Download and Install Python

Python is an interpreted language which means that the code is translated (interpreted) to binary code while the program runs.

That is different from compiled languages (C++ etc.) where the code is first compiled to binary code.

To run Python code you need to have a Python interpreter. There are different versions of Python, either Python 2 or Python 3.

To see what the difference are and to decide which one to use, please see this wiki page at python.org.

Installing Python

Python is available on most operating system, (Linux, Unix, Mac OS X and Windows)

Installing it on your computer is very easy, and on some systems it’s already there. To see if it’s already installed, open up a terminal and run this command below.

If you see a response from a Python interpreter it will include a version number in its initial display.

>> python
Python 2.7.2 (default, Jun 20 2012, 16:23:33)

If you don’t have Python installed, you can take a look at this link on how to install it on the platform that you use.

How do I run my code?

There are two ways to run the programs in Python.

Either you type in the code directly in the Python shell. When doing that you will see the result of every command that you type in.

This works best for very short programs or for testing purpose.

The other way to run the code is within a script.

Python Shell

When you are in the Python Shell, the python interpreter will translate all code for you.

To leave the help mode and return to the interpreter, we use the quit command.

The help command provides some help about Python

>>> help
Type help() for interactive help, or help(object) for help about object.
>>>

You can also use the Python Shell for doing math (please see my earlier post about using math in Python)

>>> 2 + 4
6
>>> 5 * 56
280
>>> 5 - 45
-40
>>>

To exit the Python Shell, press Ctrl+d.

Python Script

To run the program as script, open an text editor (vi, pico, nano etc.) and put in the following code:

#!/usr/bin/python 
print "hello world"

Save the file as hello.py and exit the editor.

# To execute the program, type python and the file name in the shell. 
$python hello.py

The output should be:
hello world

Python scripts can be made directly executable, like shell scripts, by putting the shebang at the beginning of the script and give the file an executable mode.

The shebang is meant for the script to recognize the interpreter type when you want to execute the script from the shell.

# The script can be given an executable mode, or permission, using the chmod command:
$ chmod +x hello.py

Now you can execute the script directly by its name.

Leave a Reply

Your email address will not be published. Required fields are marked *