Python (programming language)

from Wikipedia, the free encyclopedia
Basic data
Paradigms : multiparadigmatic
Publishing year: February 20, 1991
Designer: Guido van Rossum
Developer: Python Software Foundation , Guido van Rossum
Current  version 3.9.0   (October 5, 2020)
Typing : strong , dynamic (" duck typing ")
Important implementations : CPython, Jython , IronPython , PyPy
Influenced by: Algol 68 , ABC , Modula-3 , C , C ++ , Perl , Java , Lisp , Haskell , APL , CLU , Dylan , Icon, Standard ML
Affected: Ruby , Boo , Groovy , Cython , JavaScript , Swift
Operating system : Platform independence
License : Python Software Foundation License

Python ([ ˈpʰaɪθn̩ ], [ ˈpʰaɪθɑn ], in German also [ ˈpʰyːtɔn ]) is a universal, usually interpreted , high-level programming language . It aims to promote a legible, concise programming style. For example, blocks are not structured with curly brackets but with indentations.

Python supports several programming paradigms , such as B. object-oriented , aspect-oriented and functional programming. It also offers dynamic typing . Like many dynamic languages , Python is often used as a scripting language . The language has an open, community-based development model supported by the nonprofit Python Software Foundation , which de facto maintains the definition of the language in the CPython reference implementation .

Development history

Guido van Rossum , the developer of Python

The language was developed in the early 1990s by Guido van Rossum at the Centrum Wiskunde & Informatica in Amsterdam as the successor to the programming language ABC and was originally intended for the distributed operating system Amoeba .

The name does not (as the logo suggests) go back to the snake genus of the same name ( pythons ), but originally referred to the English comedian group Monty Python . The documentation therefore also contains some allusions to skits from the Flying Circus . Nevertheless, the association with the snake established itself , which is expressed, among other things, in the programming language Cobra and the Python toolkit "Boa". The first full version appeared in January 1994 under the name Python 1.0. Compared to earlier versions, some functional programming concepts were implemented, but these were later abandoned. From 1995 to 2000 new versions appeared, which were continuously referred to as Python 1.1, 1.2 etc.

Python 2.0 was released on October 16, 2000. New features included a fully functional garbage collection (automatic garbage collection ) and support for the Unicode character set. In version 2.6 a help was built in, which can be used to indicate which code sequences are no longer supported by the successor Python 3 and are therefore no longer executable in versions based on it.

Python 3.0 (also Python 3000) appeared on December 3, 2008 after a long development period. It includes some profound changes to the language, such as the removal of redundancies in instruction sets and outdated constructs. Since this makes Python 3.0 partially incompatible with earlier versions, the Python Software Foundation decided to continue supporting Python 2.7 in parallel with Python 3 with new versions until the end of 2019 (for information on 2-version versions that are still to be released, the end of support and help with migration, see section End of Python 2 ).


Python was designed with the greatest possible simplicity and clarity in mind. This is achieved primarily through two measures. On the one hand, the language gets by with relatively few keywords . On the other hand, the syntax is reduced and optimized for clarity. This means that Python-based scripts can be formulated much more concisely than in other languages.

During the development, Van Rossum attached great importance to a standard library that is manageable and easily expandable. This was a result of his bad experience with the ABC language , where the opposite is the case. This concept also made it possible to embed Python programs in other languages ​​as modules, e.g. B. To work around weaknesses of Python. For example, routines in machine-related languages ​​such as B. C are called. Conversely, Python can be used to write modules and plug-ins for other programs that offer the corresponding support. This is e.g. This is the case , for example, with Blender , Cinema 4D , GIMP , Maya , OpenOffice or LibreOffice , PyMOL , SPSS , QGIS or KiCad .

Python is a multi- paradigm language. This means that Python does not force the programmer into a single programming style, but rather allows the paradigm to be chosen which is most suitable for the respective task. Object-oriented and structured programming are fully supported, functional and aspect-oriented programming are supported by individual elements of the language. The data types are managed dynamically, a static type check such as B. in C ++ does not exist. Memory areas that are no longer used are released by reference counting .

Data types and structures

Data types and structures

Python has a large number of basic data types. In addition to conventional arithmetic , it transparently supports any large integers and complex numbers .

The usual string operations are supported. In Python, however, strings are immutable objects (as in Java ). Therefore, operations that are supposed to change a character string - such as B. by replacing characters - always return a new character string.

In Python everything is an object: classes, types, methods, modules, etc. The data type is always linked to the object (the value ) and not to a variable, i. H. Data types are assigned dynamically, like with Smalltalk or Lisp - and not like with Java.

Despite the dynamic type management, Python includes some type checking. This is stricter than Perl , but less strict than Objective CAML, for example . Implicit conversions according to the duck typing principle are defined for numeric types, among other things, so that, for example, a complex number can be multiplied by a long integer without an explicit type conversion.

With the format operator %there is an implicit conversion of an object into a character string. The operator ==checks two objects for (value) equality. The operator ischecks the real identity of two objects.

Collection types

Python has several types of collections , including lists, tuples , sets, and associative arrays (dictionaries). Lists, tuples and strings are sequences (sequences, fields ) and almost all know the same methods: you can iterate over the characters in a chain as well as over the elements of a list. There are also the immutable objects that cannot be changed after they have been created. Lists are e.g. B. expandable fields, whereas tuples and strings have a fixed length and are immutable.

The purpose of such immutability depends e.g. B. together with the dictionaries , a data type also known as an associative array . To ensure data consistency, the keys of a dictionary must be of the "unchangeable" type. The values entered in the dictionary , on the other hand, can be of any type.

Sets are sets of objects and are included in the standard language in CPython version 2.4 and higher. This data structure can accommodate any number of objects (different in pairs) and provides set operations such as average , difference and union .

Object system

The Python type system is tailored to the class system. Although the built-in data types are not strictly speaking classes , classes can inherit from a type . You can extend the properties of character strings or dictionaries - including integers. Python supports multiple inheritance .

The language directly supports the handling of types and classes. Types can be read out (determined) and compared and behave like objects - in fact the types (as in Smalltalk) are themselves an object. The attributes of an object can be extracted as a dictionary.


One of the design goals for Python was to make the source code easy to read. The instructions often use English keywords where other languages ​​use symbols. In addition, Python has fewer syntactic constructions than many other structured languages ​​such as C , Perl or Pascal :

  • two loop shapes
    • for for iterating over the elements of a sequence
    • while to repeat a loop as long as a logical expression is true.
  • Branches
    • if … elif … else for branches

For the last point, other programming languages ​​also offer switchand / or goto. These have been left out in Python for the sake of readability and must be represented by ifconstructs or other branching options (slices, dictionaries). Unlike many other languages, for- and whileloops can have a elsebranch. This is only carried out when the loop has been run through completely and is not breakterminated with.

Structuring by indenting

Like Miranda and Haskell, Python uses indentation as a structuring element. This idea was first proposed by Peter J. Landin and called off-side rule by him . In most other programming languages, blocks are marked with brackets or keywords, while spaces of different sizes outside of character strings have no special semantics. In these languages, the indentation to highlight a block is allowed and usually also desired, but not mandatory. For programming novices, however, the need to have a legible style is seen as an advantage.

As an example, the calculation of the factorial of an integer, once in C and once in Python:

Factorial function in C:

int factorial(int x) {
    if (x <= 1)
        return 1;

    return x * factorial(x - 1);

The same function in Python:

def factorial(x):
    if x <= 1:
        return 1

    return x * factorial(x - 1)

However, it is important to ensure that the indentations are the same throughout the entire program text. The mixed use of spaces and tabs can lead to problems, as the Python interpreter accepts tabs with a spacing of eight spaces. Depending on the configuration of the editor, tabs can be displayed with fewer than eight spaces, which can lead to syntax errors or unwanted program structuring. As a preventive measure, you can have the editor replace tab characters with a fixed number of spaces. The Python distribution contains the tabnanny module in the standard library , which helps to recognize and correct the mixing of tabs and spaces.

However, as in C, the factorial function can also be formulated in one line with a ternary operator :

The factorial function in C:

int factorial(int x) {
    return x <= 1 ? 1 : x * factorial(x - 1);

The factorial function in Python:

def factorial(x):
    return 1 if x <= 1 else x * factorial(x - 1)

Functional programming

Coconut and other extensions make functional programming in Python easier. In addition, this can also be done with conventional Python:

Expressive syntactic elements for functional programming simplify working with lists and other collection types. One such simplification is list notation, which comes from the Haskell functional programming language; here when calculating the first five powers of two:

zahlen = [1, 2, 3, 4, 5]
zweierpotenzen = [2 ** n for n in zahlen]

Because functions can appear as arguments in Python, one can also express more sophisticated constructions, such as the continuation-passing style .

Python's keyword lambdacould mislead some functional programming believers. Such lambdablocks in Python can only contain expressions, not statements. This means that such statements are generally not used to return a function. Instead, the usual practice is to return the name of a local function. The following example shows this using a simple function based on the ideas of Haskell Brooks Curry :

def add_and_print_maker(x):
    def temp(y):
        print("{} + {} = {}".format(x, y, x + y))

    return temp

This also makes currying possible in a simple way in order to break down generic function objects into problem-specific ones. Here is a simple example:

def curry(func, known_argument):
    return lambda unknown_argument: func(unknown_argument, known_argument)

If the curryfunction is called, it expects a function with two necessary parameters as well as the parameter assignment for the second parameter of this function. The return value of curryis a function that does the same thing func, but only takes one parameter.

Anonymous namespaces (so-called closures ) are linked to the above Mechanisms in Python are also easily possible. A simple example of a stack , internally represented by a list:

def stack():
    l = []

    def pop():
        if not is_empty():
            return l.pop()

    def push(element):

    def is_empty():
        return len(l) == 0

    return pop, push, is_empty

pop, push, is_empty = stack()

In this manner, the three functional objects pop, push, is_empty, to modify the stack or to check for contained elements without lbeing able to modify directly.

Exception handling

Python extensively uses the Exception Handling (English exception handling ) as a means to test error conditions. This is so integrated into Python that it is sometimes even possible to catch syntax errors and handle them at runtime.

Exceptions have some advantages over other error handling methods commonly used in programming (such as error return values ​​and global status variables). They are thread- safe and can easily be propagated to the highest program level or handled at any other level in the function call sequence. The correct use of exception handling when accessing dynamic resources also makes it easier to avoid certain security loopholes based on race conditions that can arise if access is based on status queries that are already out of date.

The Python approach suggests the use of exceptions whenever an error condition could arise. This principle is useful, for example, in the construction of robust prompts:

while True:
    num = input("Eine ganze Zahl eingeben: ")

        num = int(num)
    except ValueError:
        print("Eine _Zahl_, bitte!")

This part of the program asks the user for a number until the user enters a string that can be converted int()into an integer using . The exception handling prevents an incorrect entry from leading to a runtime error that forces the program to abort.

The interrupt signal ( SIGINToften Ctrl + C) , which is not taken into account here, can also be intercepted and handled using exception handling in Python ( except KeyboardInterrupt: …).

Standard library

The powerful standard library is one of Python's greatest strengths, which makes it suitable for many applications. The majority of it is platform-independent, so that larger Python programs often run on Unix , Windows , macOS and other platforms without change. The modules of the standard library can be supplemented with modules written in C or Python.

The standard library is specially tailored for Internet applications, with support for a large number of standard formats and protocols (such as MIME and HTTP ). Modules for creating graphical user interfaces, for connecting to relational databases and for manipulating regular expressions are also included.

Graphical user interfaces (GUI)

With the help of the supplied module Tkinter , a graphical user interface (GUI) with Tk can be quickly generated in Python (as in Perl and Tcl ) . There are also a variety of other wrappers from other providers. They provide connections ( English language bindings ) to GUI toolkits such as B. PyGTK , PyQt , wxPython , PyObjC and Py FLTK are available.

In addition to Tkinter, a module for drawing Turtle graphics is also included.

Example for the Tkinter module

import tkinter as tk

fenster = tk.Tk()
label = tk.Label(fenster, text="Hallo Welt!")

def befehl():

button = tk.Button(fenster, text="OK", command=befehl)
Example of a simple Tkinter window

Example for the Turtle graphics module

import turtle
from turtle import speed, reset, goto

turtle.x = -200
turtle.y = 200

while turtle.y != -200:
    goto(turtle.x, turtle.y)
    turtle.x = - turtle.x
    turtle.y = - turtle.y
    goto(turtle.x, turtle.y)
    goto(0, 0)
    turtle.y = - turtle.y
    turtle.x = - turtle.x
    turtle.y -= 5
Result of the specified source code

More graphics


The compact sorting algorithm Quicksort is given here as a non-trivial example :

def quicksort(liste):
    if len(liste) <= 1:
        return liste

    pivotelement = liste.pop()
    links  = [element for element in liste if element < pivotelement]
    rechts = [element for element in liste if element >= pivotelement]

    return quicksort(links) + [pivotelement] + quicksort(rechts)

In particular, the list notation for the variables on the left and right enables a compact display. For comparison, an iterative formulation of these two lines:

    links, rechts = [], []          # leere Listen für links und rechts anlegen
    pivotelement = liste.pop()      # das letzte Element aus der Liste nehmen als Referenz

    for element in liste:           # die restlichen Elemente der Liste durchlaufen ...
        if element < pivotelement:  # ... und mit dem Pivot-Element vergleichen
            links.append(element)   # wenn kleiner, dann an linke Liste anhängen
            rechts.append(element)  # ansonsten, wenn nicht kleiner, dann an rechte Liste anhängen

This is just one example of the paperwork saved by the list notation. In fact, in this case the iterative formulation is the faster one, since the "list" field is iterated only once per run and not twice as in the list notation.

Interactive use

Like Lisp , Ruby , Groovy and Perl, the Python interpreter also supports an interactive mode in which expressions can be entered at the terminal and the results can be viewed immediately. This is not only pleasant for newcomers who are learning the language, but also for experienced programmers: pieces of code can be extensively tested interactively before they are included in a suitable program.

Moreover, is with Python Shell, a command line interpreter for various Unix-like computer operating systems available, in addition to classic Unix shell commands with direct input in Python shape can handle. IPython is a popular interactive Python shell with greatly expanded functionality.


In addition to the reference implementation CPython, there is a Python interpreter implemented in Java called Jython , with which the library of the Java runtime environment is made available for Python. In addition to the interpreters, there are compilers that translate Python code into another programming language: With Cython , Python code can be translated into efficient C extensions or external C / C ++ code can be linked. There is also the IronPython compiler for the .NET or Mono platform. To use Python as a scripting language for programs in C ++ , the Boost Python library or (in newer projects) Cython are mostly used. A Python parser for Parrot and a just-in-time compiler for Python written in Python, PyPy , which was funded by the EU, are also in development. There is also a Python interpreter for microcontrollers called MicroPython .

Development environment

In addition to IDLE , which is often installed with Python and mainly consists of a text environment and a shell , some full-fledged development environments (IDEs) have also been developed for Python, for example Eric Python IDE , Spyder or PyCharm . There are also plug-ins for larger IDEs such as Eclipse , Visual Studio and NetBeans . Text editors for programmers such as Vim and Emacs can also be adapted for Python if necessary.

For the various GUI toolkits , such as B. Tkinter ( GUI Builder ), WxPython ( wxGlade ), PyQt ( Qt Designer ), PySide , PyGTK ( Glade ), Kivy or PyFLTK there are some editors with which graphical user interfaces can be set up in a comparatively simple way.

Package management

Python supports the creation of packages; distutils and setuptools help with this . The packages are stored on PyPI, the Python Package Index, and retrieved from there for installation. The package manager usually used is pip or, on old systems, easy_install . Package versions of the Anaconda (Python distribution) are managed by the package management conda .

Spread and use

Python is freely available for most common operating systems and is included in the standard scope of most Linux distributions. In order to integrate Python into web servers, WSGI is used across the web server , which avoids the disadvantages of CGI . WSGI provides a universal interface between web server and Python (framework).

A number of web application frameworks use Python, including Django , Pylons , SQLAlchemy , TurboGears , web2py , Flask and Zope . There is also a Python interpreter for the Symbian operating system, so that Python is available on various mobile phones . In version 2.5.1, Python is part of AmigaOS 4.0. In addition, several well-known commercial projects such as Google and YouTube are based in part on Python. The language is also occasionally used in the games industry, for example in EVE Online , World in Conflict and Civilization IV .

As part of the 100 dollar laptop project , Python is used as the standard user interface language. Since the $ 100 calculator is designed for school education for children, the currently running Python source code should be displayed at the push of a button when using the "Sugar" graphic user interface . This is intended to give children the opportunity to experience the information technology behind it in real life and to take a look "behind the scenes" at will.

The Raspberry Pi single-board computer (Python interpreter) was originally intended to be delivered with a Python interpreter integrated in the ROM . Even today, Python is one of the most preferred languages ​​for the Raspberry Pi. Its standard operating system, Raspberry Pi OS, comes with a large Python library for controlling the hardware.

In the scientific community enjoys Python widespread, mainly due to the easy entry into the programming and the wide range of academic libraries. Numerical calculations and the visual processing of the results in graphs are mostly done with NumPy and Matplotlib . Anaconda and SciPy combine many scientific Python libraries, making them easier to access. With TensorFlow , Keras , Scikit-learn , PyTorch etc. a. there are large libraries for research and use of machine learning and deep learning ( artificial intelligence ).

End of Python 2

Support for Python 2 has ended. The final 2-version was the 2.7.18 of April 20, 2020; as of that date, Python 2 is no longer supported. There is, however, a wide range of extensive documentation about the transition and tools that help with the migration or make it possible to write code that works with Python 2 and 3.


When defining methods, the self parameter , which corresponds to the instance whose method is called, must be specified explicitly as a parameter. Andrew Kuchling, author and long-time Python developer, perceives this as inelegant and not object-oriented. Python creator van Rossum, on the other hand, points out that it is necessary to enable certain important constructs. One of the Python principles is also "Explicit is better than implicit".

Up to version 3.0 it was criticized that calling the base class version of the same method in a method definition requires the explicit specification of the class and instance. This was seen as a violation of the DRY principle (“ Don't repeat yourself ”), and it also hindered renaming. This point of criticism has been corrected in Python 3.0.

On multiprocessor systems, the so-called Global Interpreter Lock (GIL) from CPython hinders the efficiency of Python applications that use software-based multithreading . However, this limitation does not exist under Jython or IronPython . So far there are no official plans to replace the GIL. Instead, it is recommended that you use multiple communicating processes instead of threads.

In the prevailing implementations, the execution speed is slower than many compilable languages, but similar to Perl , PHP , Dart and Ruby . This is in part because the development of CPython prioritizes code clarity over speed. One cites authorities like Donald Knuth and Tony Hoare , who advise against premature optimization. If speed problems arise that cannot be solved by optimizing the Python code, JIT compilers such as PyPy are used instead or time-critical functions are outsourced to machine-oriented languages ​​such as C or Cython .


To get you started


Further information

  • Luciano Ramalho: Fluent Python. Clear, concise, and effective programming . 1st edition. O'Reilly, Sebastopol CA (et al.) 2015, ISBN 978-1-4919-4600-8 , pp. 744 ( table of contents [PDF]).
  • Gregor Lingl: Python for Kids , bhv, 4th edition 2010, ISBN 3-8266-8673-X .
  • Farid Hajji: Das Python-Praxisbuch , Addison-Wesley, 1st edition 2008, ISBN 978-3-8273-2543-3 .
  • Hans P. Langtangen: Python Scripting for Computational Science , Springer, 3rd edition 2008, ISBN 3-540-43508-5 .
  • Michael Weigend: Object-oriented programming with Python , mitp-Verlag, 1st edition 2006, ISBN 3-8266-0966-2 .
  • Felix Bittmann: Practical Guide Python 3. Understanding and applying programming concepts . 1st edition. Books on Demand, Norderstedt 2020, ISBN 978-3-7519-0058-4 , pp. 240 ( table of contents ).

Web links

Commons : Python  - collection of images, videos and audio files
Wikibooks: Python 2 on Linux  - learning and teaching materials


For beginners

For advanced

For children

Individual evidence

  1. ^ Historique et license . (accessed on August 19, 2016).
  2. . (accessed on July 3, 2019).
  3. . (accessed on August 19, 2016).
  4. Python 3.9.0 is now available, and you can already test 3.10.0a1! . October 5, 2020 (accessed October 6, 2020).
  5. Python 3.9 released . October 5, 2020 (accessed October 6, 2020).
  6. Python 3.9 Released With Multi-Processing Improvements, New Parser . October 5, 2020 (accessed October 6, 2020).
  7. . (accessed on August 19, 2016).
  8. Why was Python created in the first place? . Python Software Foundation (accessed March 22, 2017).
  9. a b Classes The Python Tutorial . Python Software Foundation.
  10. An Introduction to Python for UNIX / C Programmers .
  11. Functional Programming HOWTO .
  12. . (accessed on August 19, 2016).
  13. .
  14. What is Python Good For? . In: General Python FAQ . Python Foundation. Retrieved September 5, 2008.
  15. What is Python? Executive summary . In: Python documentation . Python Foundation. Retrieved March 21, 2007.
  16. Official Python FAQ , and Python Tutorial, Chapter 1
  17. ^ The Cobra Programming Language . In: .
  18. Boa Constructor home . In: .
  19. Guido van Rossum: Comment on the removal of some functional concepts. Retrieved August 11, 2014 .
  20. A. Kuchling, Moshe Zadka: Documentation Python 2.0. Python Software Foundation, accessed August 11, 2014 .
  21. Python 2.6 opens the way to version 3 from October 2, 2008, accessed on October 4, 2008
  22. Guido van Rossum: Documentation Python 3.0. Python Software Foundation, February 14, 2009, accessed August 11, 2014 .
  23. 2. Lexical analysis Python 3.7.2rc1 documentation. (English)
  24. Marty Alchin: Pro Python . Ed .: Apress. 2010, ISBN 978-1-4302-2757-1 , pp. 6 (English).
  25. ^ Bill Venners: Interview with Guido van Rossum. Artima, January 13, 2003, accessed August 15, 2014 .
  26. Use of foreign language modules. Python Software Foundation, accessed September 10, 2019 .
  27. ^ Mark Lutz, David Ascher: Learning Python, 2nd Edition . In: Safari Books Online . O'Reilly Media, Inc .. December 23, 2003.
  28. Coconut (extension to Pyhon)
  29. MicroPython - Python for microcontrollers . In: .
  30. ^ Conda documentation. Retrieved February 25, 2016 .
  31. ^ Quotes about Python . Retrieved June 25, 2011.
  32. OLPC Wiki : " Python for the 100 Dollar Laptop "
  33. Karin Zühlke: “Live on stage” for the first time: Farnell shows the Raspberry Pi offspring .
  34. Python Insider: Python 2.7.18, the last release of Python 2
  35. Programming languages: Long live Python 3 - final release of Python 2
  36. Python 2 series to be retired by April 2020 , Python Software Foundation press release, December 20, 2019.
  37. Python 2.7 will get the last release in April 2020 ,, December 30, 2019.
  38. Official HOWTO:
  39. The Conservative Python 3 Porting Guide:
  40. Supporting Python 3: An in-depth guide:
  41. 2to3:
  42. six: and
  43. Python-Modernize:
  44. Python-Future / futurize:
  45. Sixer:
  46. 2to6:
  47. AM Kuchling. Retrieved September 1, 2020 .
  48. ( Memento from October 2, 2003 in the Internet Archive )
  49. Guido van Rossum: Why explicit self has to stay
  50. Tim Peters: The Zen of Python. Python Software Foundation, August 19, 2004, accessed August 12, 2014 .
  51. PEP 3135 - New Super . In: .
  52. Library and Extension FAQ - Python 3.7.0 documentation . In: .
  53. Guido van van Rossum: It isn't Easy to Remove the GIL . In: .
  54. Python C . Archived from the original on December 26, 2015. Retrieved December 25, 2015.
  55. ^ Python – Perl . Archived from the original on December 26, 2015. Retrieved December 25, 2015.
  56. Benchmark comparison Python – PHP . Archived from the original on December 26, 2015. Retrieved December 25, 2015.
  57. Benchmark comparison Python – Dart . Archived from the original on December 26, 2015. Retrieved December 25, 2015.
  58. Benchmark comparison Python – Ruby . Archived from the original on December 26, 2015. Retrieved December 25, 2015.
  59. ( page no longer available , search in web archives: Python Culture )@1@ 2Template: Dead Link /
  60. ^ Python Patterns - An Optimization Anecdote . In: .
This version was added to the list of articles worth reading on October 23, 2005 .