Learning Python from scratch #00: Intro, interpreter, IDLE environment and modules

Python is an high-level object-oriented programming language, very powerful and flexible, often used as a scripting language. Python is an interpreted language so, before you can write and run Python programs, its interpreter must be installed on your machine. On Linux and Mac OS X machines it is generally pre-installed (Python version 2 on OS X), but in a Windows environment it must be installed separately. If the installed Python version is not 3, you can download it from the Python website for any operating system.
Once installed, to launch the Python interpreter is necessary to invoke the shell command python3

Launching python

NB: running the command python instead of python3 for example on an OS X machine, will launch the version 2 of the python interpreter instead of the version 3, as shown in the following image (version 2.7.5 specifically). To associate the “python” command to version 3 you can create an alias in .bash_profile

Python 2.X prompt

Once we launch the interpreter, what is presented to us is a prompt identified by the symbol “>>>” and we can start writing the instructions to be executed.
In order to respect the tradition, let’s start with the print on the screen of the “Hello World” string:
Python Hello World

To exit the Python shell we have to enter the quit() command:
quit Python interpreter

Together with python3 also IDLE is installed. IDLE, Integrated Development Environment, is a development environment for Python that contains a shell and an editor with syntax highlighting. It can be invoked by running the idle3 command.
IDLE (Integrated Development Environment)

IDLE allows both to execute instructions directly from the shell prompt and to execute blocks of Python code written on a text file and saved with the .py extension which is exactly the extention for Python source files. These .py files containing Python code are called modules.

To create a new module in IDLE we have to select from the menu:

File -> New File

the text editor window built into IDLE will appear and we can start to write our Python code.

IDLE creating a Python module

Once finished writing the code, to run the module we have first to save it by giving it a name and then select the menu item “Run” and then the “Run Module”. Alternatively we can use the F5 key to actually run the module. At this point, the module will be executed by the interpreter.
IDLE executing Python module

To create a module however it is not strictly necessary the IDLE environment; you can create a .py file using any text editor and then run it from the operating system shell with the command python3 followed by the .py filename
python module from shell

Leave a Reply

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