INTRODUCTION TO PYTHON PROGRAMMING LANGUAGE Python is one example of a programming language. Other examples of high-level computer languages are C++, Java, Perl, Scheme, or BASIC. Although these languages differ in many details, they all share the property of having well-defined, unambiguous syntax and semantics. Although they are precise, they are designed to be used and understood by humans. In a high-level language like Python, the addition of two numbers can be expressed more naturally: c = a + b. That’s a lot easier for us to understand, but we need some way to translate the high-level language into the machine language that the computer can execute. There are two ways to do this: a high-level language can either be compiled or interpreted. A compiler is a complex computer program that takes another program written in a high-level language and translates it into an equivalent program in the machine language of some computer. Figure 1.2 shows a block diagram of the compiling process. The high-level program is called source code, and the resulting machine code is a program that the computer can directly execute. The dashed line in the diagram represents the execution of the machine code. An interpreter is a program that simulates a computer that understands a high-level language. Rather than translating the source program into a machine language equivalent, the interpreter analyzes and executes the source code instruction by instruction as necessary. Figure 1.3 illustrates the process. The difference between interpreting and compiling is that compiling is a one-shot translation; once a program is compiled, it may be run over and over again without further need for the compiler or the source code. In the interpreted case, the interpreter and the source are needed every time the program 1 runs. Compiled programs tend to be faster, since the translation is done once and for all, but interpreted languages lend themselves to a more flexible programming environment as programs can be developed and run interactively. The translation process highlights another advantage that high-level languages have over machine language: portability. The machine language of a computer is created by the designers of the particular CPU. Each kind of computer has its own machine language. A program for a Pentium CPU won’t run on a Macintosh that sports a PowerPC. On the other hand, a program written in a high-level language can be run on many different kinds of computers as long as there is a suitable compiler or interpreter (which is just another program). ASS: DOWNLOAD PYTHON INTERPRETER Python is a high-level, interpreted, interactive and object oriented-scripting language. Python was designed to be highly readable which uses English keywords frequently where as other languages use punctuation and it has fewer syntactical constructions than other languages. Python is Interpreted: This means that it is processed at runtime by the interpreter and you do not need to compile your program before executing it. This is similar to PERL and PHP. Python is Interactive: This means that you can actually sit at a Python prompt and interact with the interpreter directly to write your programs. Python is Object-Oriented: This means that Python supports Object-Oriented style or technique of programming that encapsulates code within objects. Python is Beginner's Language: Python is a great language for the beginner programmers and supports the development of a wide range of applications, from simple text processing to WWW browsers to games. History of Python: Python was developed by Guido van Rossum in the late eighties and early nineties at the National Research Institute for Mathematics and Computer Science in the Netherlands. Python is derived from many other languages, including ABC, Modula-3, C, C++, Algol-68, SmallTalk, and Unix shell and other scripting languages. Python is copyrighted, Like Perl, Python source code is now available under the GNU General Public License (GPL). Python is now maintained by a core development team at the institute, although Guido van Rossum still holds a vital role in directing it's progress. Python 1.0 was released in November 1994. In 2000, Python 2.0 was released. Python 2.7.11 is the latest edition of Python 2. 2 Meanwhile, Python 3.0 was released in 2008. Python 3 is not backward compatible with Python 2. The emphasis in Python 3 had been on the removal of duplicate programming constructs and modules so that "There should be one – and preferably only one -- obvious way to do it." Python 3.6.5 is the latest version of Python 3. Python Features: Python's feature highlights include: Easy-to-learn: Python has relatively few keywords, simple structure, and a clearly defined syntax. This allows the student to pick up the language in a relatively short period of time. Easy-to-read: Python code is much more clearly defined and visible to the eyes. Easy-to-maintain: Python's success is that its source code is fairly easy-to-maintain. A broad standard library: One of Python's greatest strengths is the bulk of the library is very portable and cross-platform compatible on UNIX, Windows, and Macintosh. Interactive Mode: Support for an interactive mode in which you can enter results from a terminal right to the language, allowing interactive testing and debugging of snippets of code. Portable: Python can run on a wide variety of hardware platforms and has the same interface on all platforms. Extendable: You can add low-level modules to the Python interpreter. These modules enable programmers to add to or customize their tools to be more efficient. Databases: Python provides interfaces to all major commercial databases. GUI Programming: Python supports GUI applications that can be created and ported to many system calls, libraries, and windows systems, such as Windows MFC, Macintosh, and the X Window system of Unix. Scalable: Python provides a better structure and support for large programs than shell scripting. Apart from the above mentioned features, Python has a big list of good features, few are listed below: Support for functional and structured programming methods as well as OOP. It can be used as a scripting language or can be compiled to byte-code for building large applications. Very high-level dynamic data types and supports dynamic type checking. Supports automatic garbage collection. It can be easily integrated with C, C++, COM, ActiveX, CORBA, and Java. The main goal of Python was to reduce the learning curve by choosing a syntax that is understandable as plain English. Python has a very simple programming philosophy, "there should be one and preferably only one obvious way to do it". This is a characteristic that sets Python apart from its competitors such 3 as Perl. Python rejects exuberant syntax and favors sparse, less cluttered syntax. Perl on the other hand sees programming as, "there is more than one way to do it". This is evident in Perl's regular expressions. The numerous backslashes, quotations and variable notations can give a novice programmer a headache. Perl is still considered a powerful language; however, the syntax can be cryptic and hard to read. Python is a multi-paradigm programming language, which allows users to code in several different programming styles. A programmer can code in a functional, object-oriented or imperative format. Python supports cross platform development and is available through open source. Advantages/Disadvantages of Python Python is a language built to exploit the advantages and circumvent the disadvantages of several programming languages. In order to create a language that developers would be pleased with Python designers’ implemented popular features from the most popular programming languages. Some of the advantages Python is well known for include: ease of learning, portability, dynamic typing and integration with other languages. Python does not use any syntax whatsoever, instead tabbing and spacing play an important role in program flow. With the absence of syntax; developers wishing to use Python need not learn any new rules. Because developers need only understand the functionality of Python to use it, it is estimated that the development process proceeds 5 to 10 times faster than in other languages such as Java or C/C++. Rapid development allows Python to be used extensively in throw-away prototyping. Python is also very robust because of its lack of syntax. Users with little to no experience with Python can quickly determine program functionality and begin re-factoring code for upgrades or bug fixes. With the capabilities of running on most operating system platforms from Windows to Linux to OS X, Python is a language with very few boundaries. A program written in Python, for one platform, using only the standard libraries can easily be ported to another operating system without need for recompiling or repackaging. Python is even capable of operating on several types of Nokia cell phones. Python does not enforce a strict type on containers or variables. With this concept, developers can design a container to hold different types of data (integer, string, float etc.) A single container for different data types means less memory is used to create distinct containers for different data types. Along with less memory usage, the user can implement the same functions on different data types rather than defining a distinct function for each type. Since Python implements the advantageous aspects of several languages it is only natural that it be able to interact with those languages. The integration of Python with languages such as Java and C/C++ allows Python to remove some stress from the interpreter. Functions can be written in another language 4 and compiled so that at runtime they do not need to be interpreted which leads to a quicker and smoother running program. Although Python is a very advantageous language it does have some downfalls. One of the main disadvantages of Python is that it is an interpreted language. Most of the other disadvantages of Python deal with the personal preferences of developers. The disadvantages of Python include: language translation, documentation and the use of modules. Rather than compiling a Python program and then running it, the program is interpreted at runtime. Languages such as Java or C/C++ have overhead before the program begins execution so that programs run much quicker, with a Python program the interpreter reads the code and determines what to do while the program is executing. Python adds the overhead on interpretation to the runtime of the program which can lead to a slower runtime. It is estimated that Python runs 1-5 times slower then Java or C/C++. Because of its lack of syntax Python is an easy language to program in; however it is not very simple to translate a Python program into any other language. The translation from Python to another language would require the user to carefully examine the structure of the code and make sure to implement the same structure using the syntax of the new programming language. Python is a constantly evolving language and thus has a module to integrate it with almost every new technology. With a constant evolution there is very little concrete documentation for Python. The official Python documentation consists of two printed books as well as a tutorial and library reference present in each release. Although there is very little official documentation the documentation that does exist is of excellent quality. Python is a very powerful language. Developers are constantly designing new modules so that Python can use the latest and greatest technologies. A major disadvantage with these new modules is that if a developer would like to make use of the technology of a certain module, the module must be imported into the project. The modules are not always part of the standard release or the standard library of Python. Python is simple to use, but it is a real programming language, offering much more structure and support for large programs than the shell has. On the other hand, it also offers much more error checking than C, and, being a very-high-level language, it has high-level data types built in, such as flexible arrays and dictionaries that would cost you days to implement efficiently in C. Because of its more general data types Python is applicable to a much larger problem domain than Awk or even Perl, yet many things are at least as easy in Python as in those languages. Python allows you to split up your program in modules that can be reused in other Python programs. It comes with a large collection of standard modules that you can use as the basis of your programs — or 5 as examples to start learning to program in Python. There are also built-in modules that provide things like file I/O, system calls, sockets, and even interfaces to graphical user interface toolkits like Tk. Python is an interpreted language, which can save you considerable time during program development because no compilation and linking is necessary. The interpreter can be used interactively, which makes it easy to experiment with features of the language, to write throw-away programs, or to test functions during bottom-up program development. It is also a handy desk calculator. Python allows writing very compact and readable programs. Programs written in Python are typically much shorter than equivalent C or C++ programs, for several reasons: • The high-level data types allow you to express complex operations in a single statement; • Statement grouping is done by indentation instead of beginning and ending brackets; • No variable or argument declarations are necessary. Python is extensible: if you know how to program in C it is easy to add a new built-in function or module to the interpreter, either to perform critical operations at maximum speed, or to link Python programs to libraries that may only be available in binary form (such as a vendor-specific graphics library). Once you are really hooked, you can link the Python interpreter into an application written in C and use it as an extension or command language for that application. By the way, the language is named after the BBC show “Monty Python’s Flying Circus” and has nothing to do with nasty reptiles. Making references to Monty Python skits in documentation is not only allowed, it is encouraged! Python 3 is available for Windows, Mac OS and most of the flavors of Linux operating system. Even though Python 2 is available for many other OSs, Python 3 support either has not been made available for them or has been dropped. Local Environment Setup If your computer uses Windows XP or 2000 or 98, first, you should verify that Python is not already installed. To check this, start a new command window and type python. If you see a message stating command not recognized, then Python does not exist on your computer. But if you see the Python prompt, >>>, then it does. If Python exists on your computer, speak to the instructor, who will advise you whether additional software is needed. Open a terminal window and type "python" to find out if it is already installed and which version is installed. Getting Python on Windows platform 6 Binaries of latest version of Python 3 (Python 3.6.5) are available on Python Official Website. In order to install Python 3.6.5, minimum OS requirements are Windows 7 with SP1. For versions 3.0 to 3.4.x, Windows XP is acceptable. The most up-to-date and current source code, binaries, documentation, news, etc., is available on the official website of Python. You can download Python documentation from the site. The documentation is available in HTML, PDF and PostScript formats. Python Official Website: http://www.python.org/ Running Python There are three different ways to start Python(1) Interactive Interpreter You can start Python from Unix, DOS, or any other system that provides you a command line interpreter or shell window. Enter python on the command line. Start coding right away in the interactive interpreter. Here is the list of all the available command line options 7 (2) Script from the Command-line A Python script can be executed at the command line by invoking the interpreter on your application, as shown in the following example. Note: Be sure the file permission mode allows execution. (3) Integrated Development Environment You can run Python from a Graphical User Interface (GUI) environment as well, if you have a GUI application on your system that supports Python. Unix: IDLE is the very first Unix IDE for Python. Windows: PythonWin is the first Windows interface for Python and is an IDE with a GUI. Macintosh: The Macintosh version of Python along with the IDLE IDE is available from the main website, downloadable as either MacBinary or BinHex'd files. 8 If you are not able to set up the environment properly, then you can take the help of you system admin. Make sure the Python environment is properly set up and working perfectly fine. First Python Program Let us execute the programs in different modes of programming. (i.) Interactive Mode Programming Invoking the interpreter without passing a script file as a parameter brings up the following prompt- Type the following text at the Python prompt and press Enter- (ii.) Script Mode Programming Invoking the interpreter with a script parameter begins execution of the script and continues until the script is finished. When the script is finished, the interpreter is no longer active. Let us write a simple Python program in a script. Python files have the extension.py. Type the following source code in a test.py file We assume that you have the Python interpreter set in PATH variable. Now, try to run this program as follows. On Linux 9 This produces the following resultThis produces the following result On Windows This produces the following result Python Identifiers A Python identifier is a name used to identify a variable, function, class, module or other object. An identifier starts with a letter A to Z or a to z or an underscore ( _ ) followed by zero or more letters, underscores and digits (0 to 9). Python does not allow punctuation characters such as @, $, and % within identifiers. Python is a case sensitive programming language. Thus, Manpower and manpower are two different identifiers in Python. Here are naming conventions for Python identifiers Class names start with an uppercase letter. All other identifiers start with a lowercase letter. Starting an identifier with a single leading underscore indicates that the identifier is private. Starting an identifier with two leading underscores ( _ ) indicates a strong private identifier. If the identifier also ends with two trailing underscores, the identifier is a language defined special name. Reserved Words The following list shows the Python keywords. These are reserved words and you cannot use them as constants or variables or any other identifier names. All the Python keywords contain lowercase letters only. 10 Lines and Indentation Python does not use braces ({}) to indicate blocks of code for class and function definitions or flow control. Blocks of code are denoted by line indentation, which is rigidly enforced. The number of spaces in the indentation is variable, but all statements within the block must be indented the same amount. For example- 11 Thus, in Python all the continuous lines indented with the same number of spaces would form a block. Multi-Line Statements Statements in Python typically end with a new line. Python, however, allows the use of the line continuation character (\) to denote that the line should continue. For example The statements contained within the [], {}, or () brackets do not need to use the line continuation character. For example Quotation in Python Python accepts single ('), double (") and triple (''' or """) quotes to denote string literals, as long as the same type of quote starts and ends the string. The triple quotes are used to span the string across multiple lines. For example, all the following are legal Comments in Python A hash sign (#) that is not inside a string literal is the beginning of a comment. All characters after the #, up to the end of the physical line, are part of the comment and the Python interpreter ignores them. 12 You can type a comment on the same line after a statement or expression Python does not have multiple-line commenting feature. You have to comment each line individually as follows- Using Blank Lines A line containing only whitespace, possibly with a comment, is known as a blank line and Python totally ignores it. In an interactive interpreter session, you must enter an empty physical line to terminate a multiline statement. 13