Python Programming Fundamentals for Class 11 and 12 – Introduction
A programming language is an artificial language designed to communicate instructions to a machine, usually computer. Programming language is used to create programs (i.e. set of instructions) that control the behavior of a machine and/or to express algorithms precisely. Programming languages uses the same general principles, so after learning any one language, it is easy to grasp another.
Open source software
Before stepping into the world of programming using open source tools, one should try to understand the definition of open source software given by “Open Source Initiative” (abbreviated as OSI). OSI is a non-profit corporation with global scope, formed to educate about and advocate the benefits of open source software, and to build bridges among different constituencies in the open source community.
Open source software is a defined as software whose source code is made available under a license that allow modification and re-distribution of the software at will. Sometimes a distinction is made between open source software and free software as given by GNU (http://www.gnu.org/). The detailed distribution terms of open source software given by OSI is given on website link: http://opensource. org/.
Python is a high-level general purpose programming language that is used in a wide variety of application domains. Python has the right combination of performance and features that demystify program writing. Some of the features of Python are listed below:
- It is a simple and easy to learn.
- Python implementation is under an open source license that makes it freely usable and distributable, even for commercial use.
- It works on many platforms such as Windows, Linux, etc.
- It is an interpreted language.
- It is an object-oriented language.
- Embeddable within applications as a scripting interface.
- Python has a comprehensive set of packages to accomplish various tasks.
Python is an interpreted language, as opposed to a compiled one, though the distinction is blurry because of the presence of the bytecode compiler (beyond the scope of this book). Python source code is compiled into bytecode, so that executing the same file is faster the second time (recompilation from source to bytecode can be avoided). Interpreted languages typically have a shorter development/debug cycle than compiled ones, and also their programs generally also run slowly. Please note that, Python uses 7-bit ASCII character set for program text.
The latest stable releases can always be found on the Python’s website (http://www.python.org/). There are two recommended production-ready Python versions at this point in time, because at the moment there are two branches of stable releases: 2.x and 3.x. Python 3.x may be less useful than 2.x, since currently there are more third party softwares available for Python 2 than for Python 3. Python 2 code will generally not run unchanged in Python 3. This book focuses on Python version 2.7.6.
Python follows modular programming approach, which is a software design technique that emphasizes separating the functionality of a program into independent, inter-changeable modules, such that each contains everything necessary to execute only one aspect of the desired functionality. Conceptually, modules represent a separation of concerns, and improve maintainability by enforcing logical boundaries between components. More information on module is provided in chapter 5.
Python versions are numbered in the format A.B.C or A.B, where A is the major version number, and it is only incremented for major changes in the language; B is the minor version number, and incremented for relatively lesser changes; C is the micro-level, and it is incremented for bug-fixed release.
“Pythonic” is a bit different idea/approach of writing program, which is usually not followed in other programming languages. For example, to loop all elements of an iterable using for statement, usually the following approach is followed:
food=['pizza','burger','noodles'] for i in range(len(food)): print(food[i])
A cleaner Pythonic approach is:
food=['pizza','burger','noodles'] for piece in food: print(piece)
Python was created in the early 1990s by Guido van Rossum at Centrum Wiskunde & Informatica (CWI, refer http://www.cwi.nl/) in the Netherlands as a successor of a language called “ABC”. Guido remains Python’s principal author, although it includes many contributions from others. When he began implementing Python, Guido van Rossum was also reading the published scripts from “Monty Python’s Flying Circus”, a BBC comedy series from the 1970s. Van Rossum thought he needed a name that was short, unique, and slightly mysterious, so he decided to call the language “Python”. In 1995, Guido continued his work on Python at the Corporation for National Research Initiatives (CNRI, visit http://www.cnri.reston.va.us/) in Reston, Virginia, where he released several versions of the software. In May 2000, Guido and the Python core development team moved to “BeOpen.com” to form the BeOpen PythonLabs team. In October of the same year, the PythonLabs team moved to Digital Creations (now Zope Corporation, visit http://www.zope.com/). In 2001, the Python Software Foundation (PSF, refer http://www.python.org/psf/) was formed, a non-profit organization created specifically to own Python-related intellectual property. Zope Corporation is a sponsoring member of the PSF.
Official Python 2.7.6 documentation can be accessed from website link: http://docs.python.Org/2/. To download an archive containing all the documents for version 2.7.6 of Python in one of various formats (plain text, PDF, HTML), follow the link: http://docs.python.Org/2/download.html.
Integrated development environment
An Integrated Development Environment (IDE) is an application that provides comprehensive facilities for software development. An IDE normally consists of a source code editor, compiler and/or interpreter, and a debugger.
IDLE is an IDE, and it is the basic editor and interpreter environment which ships with the standard distribution of Python. IDLE is the built using “Tkinter” GUI toolkit, and has the following features:
- Coded in Python, using the Tkinter GUI toolkit.
- Cross-platform i.e. works on Windows and Unix.
- Has source code editor with multiple undo, text highlighting, smart indent, call tips and many other features (shown in figure 1-2).
- Has Python shell window, also known as “interactive interpreter” (shown in figure 1-1).
“Spyder” (previously known as “Pydee”) stands for “Scientific Python Development EnviRonment” (shown in figure 1-3), and it is a powerful IDE for the Python language with advanced editing, interactive testing, debugging and introspection features. This IDE also has support of “IPython” (enhanced interactive Python interpreter) and popular Python libraries such as NumPy, Matplotlib (interactive 2D/3D plotting) etc. Some of the key features are:
- Syntax coloring (or highlighting).
- Typing helpers like automatically inserting closing parentheses etc.
- Support IPython interpreter.
- Contains basic terminal command window.
Spyder runs on all major platforms (Windows, Mac OSX, Linux), and the easiest way to install Spyder in Windows is through Python(x,y) package (visit http://www.pythonxy.com).
The expressions/codes discussed in this book are written and tested in Spyder IDE.
Python download and installation
There are many different ways to install Python, the best approach depends upon the operating system one is using, what is already installed, and how the person intends to use it. To avoid wading through all the details, the easiest approach is to use one of the pre-packaged Python distribution that provide built-in required libraries. An excellent choice for Windows operating system user is to install using a binary file which can be downloaded from official Python’s website (http://www. python, org/download/).
One can install IDLE and Spyder in Ubuntu (Linux) operating system by executing the following commands in the terminal (as shown in figure 1-4).
sudo apt-get install idle-python2.7 spyder
These can be independently installed using separate commands.
sudo apt-get install idle-python2.7 sudo apt-get install spyder
“Python(x,y)” is a free scientific and engineering development software for numerical computations, data analysis and data visualization based on Python programming language and Spyder interactive development environment, the launcher (current version 22.214.171.124) is shown in figure 1-5. The executable file of Python(x,y) can be downloaded and then installed from the website link: http://code.google.eom/p/pythonxy/. The main features of Python(x,y) are:
- Bundled with scientific oriented Python libraries and development environment tools.
- Extensive documentation of various Python packages.
- Providing all-in-one setup program, so that the user can install or uninstall all these packages and features by clicking one button only.
“Object” (also called “name”) is Python’s abstraction for data. All data in a Python program is represented by objects or by relations between objects. Every object has an identity, a type and a value. An object’s identity never changes once it has been created; it can be thought of it as the object’s address in memory. The id () function returns an integer representing its identity (currently implemented as its address). An object’s type determines the operations that the object supports and also defines the possible values for objects of that type. An object’s type is also unchangeable and the type () function returns an object’s type. The value of some objects can change. Objects whose value can change are said to be “mutable”; objects whose value is unchangeable once they are created are called “immutable”. In the example below, object a has identity 31082544, type int and value 5.
>>> a=5 >>> id(a) 31082544 >>> type(a) <type 'int'>
Some objects contain references to other objects; these are called “containers”. Examples of containers are tuples, lists and dictionaries. The value of an immutable container object that contains a reference to a mutable object can change when the latter’s value is changed; however the container is still considered immutable, because the collection of objects it contains cannot be changed. So, immutability is not strictly the same as having an unchangeable value.
An object has attribute(s), which are referenced using dotted expressions. For example, if an object abc has an attribute pq, then it would be referenced as abc . pq. In the following example, upper () is an attribute of var object.
>>> var='hello' >>> var.upper() 'HELLO'
In the above example, upper () is function on some object var, and this function is called “method”. More information on “method” is given in chapter 6.
One of Python’s most useful features is its interactive interpreter. It allows very fast testing of ideas without the overhead of creating test files, as is typical in most programming languages. However, the interpreter supplied with the standard Python distribution is somewhat limited for extended interactive use. IPython is a good choice for comprehensive environment for interactive and exploratory computing.
To start interactive mode, launch Python with no arguments (possibly by selecting it from your computer’s main menu). It is a very powerful way to test out new ideas or inspect modules and packages.
Interactive mode prompts for the next command with the “primary prompt”, usually three greater- than signs (>>>); a continuation line is prompted with the “secondary prompt”, which is by default represented by three dots (…). The interpreter prints a welcome message stating its version number and some additional information before printing the first prompt:
$ python Python 2.7 (#1, Feb 28 2010, 00:02:06) Type "help", "copyright", "credits" or "license" for more information. >>>
Continuation lines are needed when entering a multi-line statement. As an example, take a look at this if statement:
>>> the_world_is_flat = 1 >>> if the_world_is_flat: ........ print("Be careful not to fall off!") ........ Be careful not to fall off!
Invoking Python interpreter
In Unix/Linux platforms, the Python interpreter is usually installed at /usr/local/bin/python. It is possible to start interpreter by typing the following command (same command for MS Windows)
in the shell. Since the choice of the directory where the interpreter lives is an installation option, other places are possible (e.g., /usr/local/python is a popular alternative location).
On Windows machines, the Python installation is available at path C:\Python27, though, this can be changed when running the installer. To add this directory to Path environmental variable, type the following command into the MS DOS command prompt:
Inputting end-of-file character (Control-D on Unix, Control-Z on Windows) at the primary prompt causes the interpreter to exit. If that does not work, you can exit the interpreter by typing the following command:
>>> quit ( )
If Python interpreter is closed and then invoked again, the definitions that were made (functions, variables etc.) are lost. Therefore, to write a long program, the programmer should use a text editor to prepare the input for the interpreter and run it with that file as input instead. This is known as creating a “script”. Most of the examples in this book are discussed using interactive mode, but few scripts are also incorporated.
This section will demonstrate to write a simple Python program, which prints “Hello World”. Type the following lines in IDLE text editor and save it as “HelloWorld.py”.
#! /usr/bin/env python print ('Hello world')
The first line is called “shebang line” or “hashbang line” (more information in next section). The second line gives the output: “Hello World”. There are numerous ways to run a Python program. The simplest approach is to press F5 functional key after saving the program in IDLE text editor. The output is shown below:
>>> Hello world
Executing Python script
As discussed in previous section, Python script can be executed using F5 functional key, from Python’s IDE. It can also be executed using command prompt by typing the following command:
$ python<file name>
On different platforms, the execution of Python scripts (apart from running from inside Python’s IDE) can be carried out as follows:
On Unix/Linux system, Python script can be made directly executable, like shell scripts, by including the following expression as first line of the script (assuming that the interpreter is on the user’s PATH) and giving the file an executable mode.
#! /usr/bin/env python
The ‘# !’ must be the first two characters of the file. Note that the hash or pound character ‘#’ is used to start a comment in Python. The script can be given an executable mode/permission, using the chmod command:
$ chmod +x HelloWorld.py
On Windows system, the Python installer automatically associates .py files with python.exe, so that double-click on a Python file will run it as a script. The extension can also be .pyw, in that case, the console window that normally appears is suppressed. At MS DOS prompt, the Python script can be executed by going to the directory containing the script and just entering the script name (with extension).
A “syntactic metalanguage” is a notation for defining the syntax of a language by use of a number of rules. A syntactic metalanguage is an important tool of computer science. Since the definition of the programming language “Algol 60”, it has been a custom to define the syntax of a programming i
language formally. Algol 60 was defined with a notation now known as “Backus-Naur Form” (BNF). This notation has proved a suitable basis for subsequent languages, but has frequently been extended or slightly altered. There are many different notations which are confusing and has prevented the advantages of formal unambiguous definitions from being widely appreciated. “Extended BNF” (abbreviated as EBNF, based on Backus-Naur Form) brings some order to the formal definition of syntax and is useful not just for the definition of programming languages, but for many other formal definitions. Please refer international standard document (ISO/IEC 14977:1996(E)) for detailed information on EBNF (website link: http://standords.iso.org/ittf/PubliclyAvoilobleStandards/).