Last Modified: 3-12-2010

IUSB

Home

Python Tutorial

Introduction to Python
Installation
Programming Fundamentals

Python Tutorial - Introduction

Python was developed to be an easily learned, easy to use, yet very powerful programming language. People with little or no computer experience as well as seasoned programmers can all quickly get up to speed and start using Pythons extensive capabilities. A Python program written under MS Windows will run unchanged on Linux or Mac environments. Python allows users to access GUI, Internet, and multimedia capabilities, with a minimum of effort. Python is installed as standard on Linux and Mac systems. Windows users can begin programming in Python quickly and easily by following the Installation Instructions then begin using the tutorial on this site starting with Programming Fundamentals. Outlined below are several technical reasons for starting the language. Otherwise, let's Get started.

Primary factors for using Python

Software Quality

For many, Python's focus on readability, coherence, and software quality in general sets it apart from other tools in the scripting world. Python code is designed to be readable, and hence, reusable and maintainable - much more so than traditional scripting languages. The uniformity of Python code makes it easy to understand, even if you did not write it. In addition, Python has deep support for more advanced software reuse mechanisms, such as object-oriented programming (OOP).

Developer Productivity

Python boosts developer productivity many times beyond compiled or statically typed languages such as C, C++, and Java. Python code is typically one-third to one-fifth the size of equivalent C++ or Java code. That means there is less to type, less to debug, and less to maintain after the fact. Python programs also run immediately, without the lengthy compile and link steps of some other tools, further boosting programmer speed.

Program Portability

Most Python programs run unchanged on all major computer platforms. Porting Python code between Linux and Windows, for example, is usually just a matter of copying a script's code between machines. Moreover, Python offers multiple options for coding portable graphical user interfaces, including program launches and directory processing, are as portable in Python as they possibly can be.

Support Libraries

Python comes with a large collection of prebuilt and portable functionality, known as the standard library. This library supports an array of application-level programming tasks, from text pattern matching to network scripting. In addtion, Python can be extended with both homegrown libraries and a vast collection of third-party support software. Python's third-party domain offers tools for website construction, numeric programming, serial port access, game development, and much more. The NumPy extension, for instance has been described as a free and more powerful equivalent to the Matlab numeric programming system.

Component Integration

Python scripts can easily communicate with other parts of an application, using a variety of integration mechanisms. Such integrations allow Python to be used as a product customization and extension tool. Today, Python code can invoke C and C++ libraries, can be called from C and C++ programs, can integrate with Java components, can communicate over frameworks such as .COM and .NET, and can interact over networks with interfaces like SOAP, XML-RPC, and CORBA. It is not a standalone tool.

Software Quality

By design, Python implements a deliberately simple readable syntax, and a highly coherent programming model. As a slogan at a recent Python conference attests, the net result is that Python seems to "fit your brain" - that is, features of the language interact in consistent and limited ways, and follow naturally from a small set of core concepts. This makes the language easier to learn, understand, and remember. In practice, Python programmers do not need to constantly refer to manuals when reading or writing code; it's a consistently designed system that many find yields surprisingly regular-looking code.

By philosophy, Python adopts a somewhat minimalist approach. This means that although there are usually multiple ways to accomplish a coding task, there is usually just one obvious way, a few less obvious alternatives, and a small set of coherent interactions everywhere in the language. Moreover, Python doesn't make arbitrary decisions for you; when interactions are ambiguous, explicit intervention is preferred. In the Python way of thinking, explicit is better than implicit, and simple is better than complex.

Beyond such design themes, Python includes tools such as modules and OOP that naturally promote code reusability. And because Python is focused on quality, so too, naturally, are Python programmers.

Developer Productivity

During the great Internet boom of the mid to late 1990s, it was difficult to find enough programmers to implement software projects; developers were asked to implement systems as fast as the Internet evolved. Now, in the post-boom era of layoffs and economic recession, the picture has shifted. Today, programming staffs are often asked to accomplish the same tasks with even fewer people.

In both of these scenarios, Python has shined as a tool hat allows programmers to get more done with less effort. It is deliberately optimized for speed of development - it's simple syntax, dynamic typing, lack of compile steps, adn built-in toolset allow programmers to develop programs in a fraction of the time needed when using some other tools. The net effect is that Python typically boosts developer productivity many times beyond the levels supported by traditional languages. That's good news in both boom and bust times, and everywhere the software industry goes inbetween.

Python is an Object Oriented Scripting Language

Python is a general purpose programming language that is often applied in scritping roles. It is commonly defined as an object oriented scripting language - a definition that blends support for OOP with an overall orientation toward scripting roles. In fact, people often use the word 'script' instead of 'program' to describe a Python code file.

Because the term 'Scripting Language' has so many different meanings to different observers, some would prefer that it not be applied to Python at all. In fact, people tend to make three very different associations with Python:

Shell Tools

Sometimes when people hear Python described as a scripting language, they think it means that Python is a tool for coding operating-system-oriented scripts. Such programs are often launched from console command lines, and perform tasks such as processing text files and launching other programs.

Python programs can and do serve such roles, but this is just one of the dozens of common Python application domains. It is not just a shell-script language.

Control Language

To others, scripting refers to a 'glue' layer used to control and direct other application components. Python programs are indeed often deployed in the context of larger applications. For instance, to test hardware devices, Python programs may call out to components that give low-level access to a device. Similarly, programs may run bits of Python code at strategic points to support end-user product customization without having to ship and recompile the entire system's source code.

Python's simplicity makes it a naturally flexible control tool. Technically, though, this is also just a common Python role; many Python programmers code standalone scripts without ever using or knowing any integrated components. It is not just a control language.

Ease of Use

Probably the best way to think of the term 'scripting language' is that it refers to a simple language used for quickly coding tasks. This is especially true when the term is applied to Python, which allows much faster program development than compiled languages like C++. Its rapid development cycle fosters an exploratory, incremental mode of programming that has to be experienced to be appreciated.

Don't be fooled, though - Python is not just for simple tasks. Rather, it makes tasks simple by its ease of use and flexibility. Python has a simple feature set, but it allows programs to scale up in sophistication as needed. Because of that, it is commonly used for quick tactical tasks and longer-term strategic development.

Concerns Related to Programming in Python

The current standard implementations of Python today compile the source code statements into an intermediate format known as byte code, and then interpret the byte code. Byte code provides portability, as it is a platform-independent format. However, because Python is not compiled all the way down to binary machine code, Python programs typically run slower than in a fully compiled language like C/C++.

Whether or not this is a concern for you depends on your application. Python has been optimized numerous times, so Python code runs relatively fast enough by itself in most application domains. Furthermore, whenever you do something 'real' in a Python script, like process a file or construct a GUI, your program is actually running at C speed, since such tasks are immediately dispatched to C code inside the Python interpreter. More fundamentally, Python's speed-of-development gain is often far more important than any speed-of-execution loss, especially given modern computer speeds.

Where Python is used Today

Python is an open source language, so a tally on the number of users is somewhat difficult. Python is automatically included in Linux and Macintosh distributions, as well as some products and hardware.

In general, though, Python enjoys a large user base, and a very active developer community. Because Python has been around for almost 20 years and has been widely used, it is also very stable and robust. Besides being employed by individual users, Python is also being applied in revenue generating products for several well known corporations:

  • Google makes extensive use of Python in its web search system, and employs Python's creator.
  • The YouTube video sharing service is largely written in Python.
  • The BitTorrent peer-to-peer file sharing system in a Python program.
  • Intel, Cisco, Hewlett-Packard, Seagate, Qualcomm, and IBM use Python for hardware testing.
  • Industrial Light & Magic, Pixar and other use Python in the production of movie animation.
  • JPMorgan, Chase, UBS, Getco, and Citadel apply Python for financial market forecasting.
  • NASA, Los Alamos, Fermilab, JPL, and others use Python for scientific programming tasks.
  • iRobot uses Python to develop commercial robotic vacuum cleaners.
  • ESRI uses Python as an end-user customization tool for its popular GIS mapping products.
  • The NSA uses Python for cryptography and intelligence analysis.
  • The IronPort email server product uses more than 1 million lines of Python code to do its job.

Python Application Capabilities

Besides being a well-designed programming language, Python is also useful for accomplishing real-world tasks - which are the sorts of things developers do day in and day out. It's commonly used in a variety of domains, as a tool for scripting other components and implementing standalone programs. In fact, as a general purpose language, Python's roles are virtually unlimited: you can use it for everything from web site development and gaming, to robotics and spacecraft control.

However, the most common Python roles currently seem to fall into a few broad categories. The next few sections describe some of Python's most common applications today, as well as tools used in each domain.

Systems Programming

Python's built-in interfaces to operating-system services make it ideal for writing portable, maintainable system-administration tools and utilities (sometimes called shell tools). Python programs can search files and directory trees, launch other programs, do parallel processing with processes and threads and so on.

Python's standard library comes with POSIX bindings and support for all the usual OS tools: environment variables, files, sockets, pipes, processes, multiple threads, regular expression pattern matching, command line arguments, standard stream interfaces, shell-command launchers, filename expansion, and more. In addition, the bulk of Python's system interfaces are designed to be portable; for example, a script that copies directory trees typically runs unchanged on all major Python platforms.

GUIs

Python's simplicity and rapid turnaround also make it a good match for graphical user interface (GUI) programming. Python comes with a standard object-oriented interface to the Tk GUI API called Tkinter, which allows Python programmers to implement portable GUIs with a native look and feel. Python/Tkinter GUIs run unchanged on MS Windows, X Windows (on Unix and Linux), and the Mac OS. A free extension package, PMW adds advanced widgets to the Tkinter toolkit. In addtion, the wxPython GUI API, based on a C++ library, offers an alternative toolkit for constructing portable GUIs in Python.

Higher-level toolkits such as PythonCard and Dabo are built on top of base APIs such as wxPython and Tkinter. With the proper library, you can also use other GUI toolkits in Python, such as Qt, GTK, MFC, and Swing. For applications that run in web browsers, or have simple interface requirements, both Jython and Python server-side GCI scripts provide additional user interface options.

Internet Scripting

Python comes with standard Internet modules that allow Python programs to perform a wide variety of networking tasks, in both client and server modes. Scripts can communicate over sockets; extract form information sent to server-side CGI scripts; transfer files by FTP; process XML files; send, receive, compose, and parse email; fetch web pages by URLs; parse the HTML and XML of fetched web pages; communicate over XML-RPC, SOAP, and Telnet; and more. Python's libraries make these tasks remarkably simple.

In addition, there is a large collection of third-party tools available on the Web for doing internet programming in Python. For instance, the HTMLGen system generates HTML files from Python class-based descriptions, the mod_python package runs Python efficiently with the Apache web server and supports server-side templating with its Python Server Pages, and the Jython system provides for seamless Python/Java integration, and supports coding of server-side applets that run on clients. In addition, full-blown web development packages for Python, such as Django, TurboGears, Pylons, Zope, and WebWare, support quick construction of full-featured and production-quality web sites with Python.

Component Integration

We discussed the component integration role earlier when describing Python as a control language. Python's ability to be extended by and embedded in C and C++ systems makes it useful as a flexible glue language for scripting the behavior of other systems and components. For instance, integrating a C library into Python enables Python to test and launch the library's components, and embedding Python in a product enables onsite customizations to be coded without having to recompile the entire product, or ship its source code at all.

Tools such as the SWIG and SIP code generators can automate much of the work needed to link compiled components into Python for use in scripts. And larger frameworks, such as Python's COM support on MS Windows, the Jython Java-based implementation, the IronPython .NET-based implementation, and various CORBA toolkits for Python, provide alternative ways to script components. On Windows, for example, Python scripts can use frameworks to script MS Word and Excel.

Database Programming

For traditional database demands, there are Python interfaces to all commonly used relational database systems - Sybase, Oracle, Informix, ODBC, MySQL, PostgreSQL, SQLite, and more. The Python world has also defined a portable database API for accessing SQL database systems from Python scripts, which looks the same on a variety of underlying database systems. For instance, because vendor interfaces implement the portable API, a script written to work with the free MySQL system will work largely unchanged on other systems (such as Oracle); all you have to do is replace the underlying vendor interface.

Python's standard pickle module provides a simple object persistence system - it allows programs to easily save and restore entire Python objects to files and file-like objects. On the Web, you'll also find a third-party system name ZODB that provides a complete object-oriented database system for Python scripts, and another called SQLObject that maps relational tables onto Python's class model. And, as of Python 2.5, SQLite is a standard part of Python itself.

Rapid Prototyping

With Python programs, components written in Python and C look the same. Because of this, it's possible to prototype systems in Python initially, and then move selected components to a compiled language such as C or C++ for delivery. Unlike some prototyping tools, Python doesn't require a complet rewrite once the prototype has solidified. Parts of the system that don't require the efficiency of a language such as C++ can remain coded in Python for ease of maintenance and use.

Numeric and Scientific Programming

The NumPy numeric programming extension for Python mentioned earlier includes such advanced tools as an array object, interfaces to standard mathematical libraries, and much more. By integrating Python with numeric routines coded in a compiled language for speed, NumPy turns Python into a sophisticated yet easy-to-use numeric programming language tool, which can often replace existing code written in traditional compiled languages such as Fortran or C++. Addtional numeric tools for Python support animation, 3D visualization, parallel processing, and so on.

Gaming, Images, AI, XML, Robots

Python is commonly applied in many domains. For example, you can do graphics and game programming in Python with the pygame system; image processing with the PIL package and others; robot control programming with the PyRo toolkit; XML parsing with the xml library package, the xmlrpclib module, and third party extensions; AI programming with neural network simualation and expert system shells; and natural language analysis with the NTLK package. You can even play solitaire with the PySol program. You'll find support for many such fields at the Vaults of Parnassus, and the newer PyPI web sites.

In general, many of these specific domains are largely just instances of Python's component integration role in action again. Adding Python as a frontend to libraries of components written in a compiled language such as C makes Python useful for scripting in a wide variety of domains. As a general purpose language that supports integration, Python is widely applicable.

Python's Technical Strengths

Naturally, this is a developer's question. If you don't already have a programming background, the language in the next few sections may be a bit baffling - don't worry, we'll explore all of these terms in more detail as we proceed. For developers, though, here is a quick introduction to some of Python's top technical features.

Python Is Object Oriented

Python is an object-oriented language, from the ground up. Its class model supports advanced notions such as polymorphism, operator overloading, and multiple inheritance; yet, in the context of Python's simple syntax and typing, OOP is remarkably easy to apply. In fact, if you don't understand these terms, you'll find they are much easier to learn with Python than with just about any other OOP language available.

Besides serving as a powerful code structuring and reuse device, Python's OOP nature makes it ideal as a scripting tool for object-oriented languages such as C++ and Java. For example, with the appropriate glue code, Python programs can subclass classes implemented in C++, Java, and C#.

Of equal significance, OOP is an option in Python; you can go far without having to become an object guru all at once. Much like C++, Python supports both procedural and object-oriented programming modes. Its object-oriented tools can be applied if and when constraints allow. This is especially useful in tactical development modes, which preclude design phases.

Python is Free

Python is completely free to use and distribute. As with other open source software, such as Tcl, Perl, Linux and Apache, you can fetch the entire Python system's source code for free on the Internet. There are no restrictions on copying it, embedding it in your systems, or shipping it with your products. In fact, you can even sell Python's source code, if you are so inclined.

But don't get the wrong idea: "free" does not mean "unsupported". On the contrary, the Python online community responds to user queries with a speed that most commercial software vendors would do well to notice. Moreover, because Python comes with complete source code, it empowers developers, leading to the creation of a large team of implementation experts. Although studying or changing a programming language's implementation isn't everyone's idea of fun, it's comforting to know that it's available as a final resort and ultimate documentation source. You're not dependent on the whims of a commercial vendor.

Python is Portable

The standard implementation of Python is written in portable ANSI C, and it compiles and runs on virtually every major platform currently in use. For example, Python programs run today on everything from PDAs to supercomputers. As a partial list, Python is available on:

  • Linux and Unix Systems
  • Microsoft Windows and even DOS
  • MAC OS
  • BeOS, OS/2, VMS, and QNX
  • Real-time systems such as VxWorks
  • Cray supercomputers and IBM mainframes
  • PDAs running Palm OS, PocketPC, and Linux
  • Cell phones running Symbian OS and Windows Mobile
  • Gaming consoles and iPods

Besides the language interpreter itself, the standard library modules that ship with Python are also implemented to be as portable across platform bounaries as possible. Further, Python programs are automatically compiled to portable byte code, which runs the same on any platform with a compatible version of Python installed.

What this means is that Python programs using the core language and standard libraries run the same on Linux, Windows, and most other systems with a Python interpreter. Most Python ports also contain platform-specific extensions, but the core Python language and libraries work the same everywhere. As mentioned earlier, Python also includes an interface to the Tk GUI toolkit called Tkinter, which allows Python programs to implement full-featured graphical user interfaces that run on all major GUI platforms without program changes.

Python is Powerfull

From a features perspective, Python is something of a hybrid. Its toolset places it between tradtional scripting languages (such as Tcl, Scheme, and Perl), and systems development languages (such as C, C++ and Java). Python provides all the simplicity and ease of use of a scripting language, alonge with more advanced software engineering tools typically found in compiled languages. Unlik some scripting languages, this combination makes Python useful for large-scale development projects. As a preview, here are some of the things you'll find in Python's toolbox:

Dynamic Typing

Python keeps track of the kinds of objects your program uses when it runs; it doesn't require complicated type and size declarations in your code. In fact, there is no such thing as a type or variable declaration anywhere in Python. Because Python code does not constrain data types, it is also usually automatically applicable to a whole range of objects.

Automatic Memory Management

Python automatically allocates objects and reclaims them when they are no longer used, and most grow and shrink on demand. As you'll learn, Python keeps track of low-level memory details so you don't have to.

Programming-in-the-large support

For building larger systems, Python includes tools such as modules, classes, and exceptions. These tools allow you to organize systems into components, use OOP to reuse and customize code, and handle events and errors gracefully.

Built-in object types

Python provides commonly used data structures such as lists, dictionaries, and strings as intrinsic parts of the language. These data structures are both flexible and easy to use. For instance, built-in objects can grow and shrink on demand, can be arbitrarily nested to represent complex information, and more.

Built-in Tools

To process all those object types, Python comes with powerful and standard operations, including concatenation, slicing, sorting, mapping and more.

Library Utilities

For more specific tasks, Python also comes with a large collection of precoded library tools that support everything from regular-expression matching to networking. Python's library tools are where much of the application-level action occurs.

Third-Party Utilities

Because Python is open-source, developers are encouraged to contribute precoded tools that support tasks beyond those supported by its built-ins; on the Web, you'll find free support for COM, imaging, CORBA ORBs, XML, database access, and much more.

Despite the array of tools in Python, it retains a remarkably simple syntax and design. The result is a powerful programming tool with all the usability of a scripting language.

Python is Mixable

Python programs can easily be 'glued' to components written in other languages in a variety of ways. For example, Python's C API lets C programs call and be called by Python programs flexibly. That means you can add functionality to the Python system as needed, and use Python programs within other environments or systems.

Mixing Python with libraries coded in languages such as C or C++, for instance, makes it an easy-to-use frontend language and customization tool. As mentioned earlier, this also makes Python good at rapid prototyping; systems may be implemented in Python first, to leverage its speed of development, and later, moved to C for delivery, one piece at a time, according to performance demands.

Python is Easy to Use

To run a Python program, you simply type it and run it. There are no intermediate compile and link steps, like there are for languages such as C or C++. Python executes programs immediately, which makes for an interactive programming experience and rapid turnaround after program changes - in many cases, you can witness the effect of a program change as fast as you can type it.

Of course, develoment cycle turnaround is only one aspect of Python's ease of use. It also provides a deliberately simple syntax and powerful built-in tools. In fact, some have gone so far as to call Python "executable pseudocode." Because it eliminates much of the complexity in other tools, Python programs are simpler, smaller and more flexible than equivalent programs in languages like C, C++, and Java.

Installation Home Programming Fundamentals