Python Language


This draft deletes the entire topic.

expand all collapse all

Examples

  • 176

    Python is a high-level, structured, open-source, dynamically typed programming language that can be used for a wide variety of programming tasks.

    Two major versions of Python are currently in active use:

    • Python 2.x is the legacy version and will only be updated for security fixes until 2020. No new features will be implemented.
    • Python 3.x is the current version and is under active development.

    You can download and install the latest version of Python 2 or Python 3 at the official website. See Python 2 vs. Python 3 for more info on the differences between both versions. In addition, a number of third-parties offer re-packaged versions of Python that add commonly used libraries and other features to ease setup for common use cases—such as math, data-intensive or scientific use. See the list at the official website.

    Hello World Python file

    Create a new file hello.py containing the following line:

    print('Hello, World')
    
    Python 2.x2.7

    If using Python 2, you may also type the line below. Note that this is not valid in Python 3 and thus not recommended because it reduces cross-version code compatibility.

    print 'Hello, World'
    
    Python 2.x2.6

    You can use the Python 3 print function in Python 2 with the following import:

    from __future__ import print_function
    

    Python 2 has a number of functionalities that can be optionally ported from Python 3 using the __future__ module, as discussed here.

    Hello, World in Python using IDLE

    IDLE is the 'Integrated Development and Learning Environment' for Python. It is installed automatically with Python and can be used as a Python programming editor to write and run programs.

    Steps for creating Hello, World program in IDLE

    • Open IDLE on your system of choice.
      • In older versions of Windows it lives in All Programs under the Windows menu.
      • In Windows 8+ search for IDLE, or find it in the apps that are present in your system.
      • On unix-based (including Mac) systems you can open it from the shell by typing $ idle python_file.py.
    • You will find a shell with options along the top.
    • There appears a prompt of three right angle brackets:
    >>>
    

    Now write the following code in the prompt:

    >>>print("Hello, World")
    

    Click Enter:

    >>>print("Hello, World")
       Hello, World
    

    The main purposes of the IDLE are:

    • Multi-window text editor with syntax highlighting, autocompletion, smart indent and other. Python shell with syntax highlighting.
    • Integrated debugger with stepping, persistent breakpoints, and call stack visibility.
    • Auto Indentation (useful for beginners learning about Python's indentation).
    • You can also save the Python program as .py files and run them and edit them later at any them using IDLE.

    Execute with Python

    Verify that you have Python installed by running the following command in your favorite terminal (eg. cmd prompt, LXTerminal):

    $ python --version
    
    Python 2.x2.7

    If you have Python 2 installed, and it is your default version (see Troubleshooting for more details) you should see something like this:

    $ python --version
    Python 2.7.12
    
    Python 3.x3.0

    If you have Python 3 installed, and it is your default version (see Troubleshooting for more details) you should see something like this:

    $ python --version
    Python 3.5.2
    
    Python 3.x3.0

    If using Python 3, you may run across the issue that $ python --version leaves you with a Python 2.x version, in that case, use $ python3 instead of $ python. This is because Python 2.x is installed on your system (this is the case by default on MacOS and many Linux distributions). Python 3.x doesn't override that behavior by default for legacy reasons. If you have multiple Python installations you can determine which you have by using the which command:

    $ which python
    

    This will show you the path to the python executable you're using.

    In your terminal, navigate to the directory containing the file hello.py.

    For those who aren't familiar with the terminal, use cd <dir> to change directories. On most platforms, users can also Shift-right-click and select Open command window/terminal here from file manager when in a folder where hello.py is contained. MacOS users can drag any folder from a Finder window into the terminal to copy the path to that folder.

    Type python hello.py, then hit the Enter key.

    $ python hello.py
    Hello, World
    

    You can also substitute hello.py with the path to your file. For example, if you have the file in your home directory and your user is "user" on Linux, you can type python /home/user/hello.py.

    You should see "Hello, World" printed to the console.

    Launch an interactive Python shell

    By executing the python command in your terminal, you can swap into an interactive Python shell, also called a REPL (read-evaluate-print loop):

    $ python
    Python 3.5.2 (default, Jun 28 2016, 08:46:01) 
    [GCC 6.1.1 20160602] on linux
    Type "help", "copyright", "credits" or "license" for more information.
    >>> print('Hello, World')
    Hello, World
    >>>
    

    Alternatively, start the interactive prompt and load file with python -i <file.py>.

    In command line, run:

    % python -i hello.py
    "Hello World"
    >>>
    

    The interactive Python shell is a very practical tool for learning and testing the features of the Python language while playing with the values and syntax interactively.

    Try the interactive Python shell online.

    Run a module as a script

    Raw scripts run in Python do not have a package associated with them, and so relative imports can cause problems. If your script must understand the package it is in to import other Python you've written, use the -m flag to run it as a module. Here is a trivial example that allows you to effectively elide the .py extension:

    % python -m hello
    'Hello World'
    

    In most cases, though, you would be referencing a particular entry point into packaged Python code:

    % python -m foo.hello
    

    In this case, Python will find the modules (based on __init__.py files) starting in the execution directory. It will then execute the hello script with package foo. Other code available in other discovered packages (such as, perhaps, foo.world - another sub-package of the root package) will also be available to the executed script (hello).

    Run commands as a string

    Python can be passed arbitrary code as a string in the shell:

    % python -c 'print("Hello, World)'
    Hello, World
    

    This can be useful when concatenating the results of scripts together in the shell.

    Shells and Beyond

    Shells - So far, we have discussed different ways to run code using Python's native interactive shell. Shells use Python's interpretive power for experimenting with code real-time. Alternative shells include IDLE - a pre-bundled GUI, IPython - known for extending the interactive experience, etc.

    Programs - For long-term storage you can save content to .py files (a.k.a. modules) and edit/execute them as scripts or programs with external tools e.g. shell, IDEs, Jupyter notebooks, etc. Intermediate users may consider using these tools, however, the methods discussed in this topic are sufficient at minimum for getting started.

    Common guidelines for Python coding standards are specified in the PEP8 spec.

  • 66

    To create a variable in Python, all you need to do is specify the variable name, and then assign a value to it. Python uses = to assign values to variables. There's no need to declare a variable in advance (or to assign a data type to it), assigning a value to a variable itself declares and initializes the variable with that value. There's no way to declare a variable without assigning it an initial value.

    a = 2
    print(a)
    # Out: 2
    
    b = 9223372036854775807
    print(b)
    # Out: 9223372036854775807
    
    pi = 3.14
    print(pi)
    # Out: 3.14
    
    c = 'A'
    print(c)
    # Out: A
    
    name = 'John Doe'
    print(name)
    # Out: John Doe
    
    q = True
    print(q)
    # Out: True
    
    x = None
    print(x)
    # Out: None
    

    Even though there's no need to specify a data type when declaring a variable in Python, while allocating the necessary area in memory for the variable, the Python interpreter automatically picks the most suitable built-in type for it:

    a = 2
    print(type(a))
    # Out: <type 'int'>
    
    b = 9223372036854775807
    print(type(b))
    # Out: <type 'int'>
    
    pi = 3.14
    print(type(pi))
    # Out: <type 'float'>
    
    c = 'A'
    print(type(c))
    # Out: <type 'str'>
    
    name = 'John Doe'
    print(type(name))
    # Out: <type 'str'>
    
    q = True
    print(type(q))
    # Out: <type 'bool'>
    
    x = None
    print(type(x))
    # Out: <type 'NoneType'>
    

    You can assign multiple values to multiple variables in one line. Note that there must be the same number of arguments on the right and left sides of the = operator:

    a, b, c = 1, 2, 3
    print(a, b, c)
    # Out: 1 2 3
    
    a, b, c = 1, 2
    => Traceback (most recent call last):
    =>   File "name.py", line N, in <module>
    =>     a, b, c = 1, 2
    => ValueError: need more than 2 values to unpack
    
    a, b = 1, 2, 3
    => Traceback (most recent call last):
    =>   File "name.py", line N, in <module>
    =>     a, b = 1, 2, 3
    => ValueError: too many values to unpack
    

    You can also assign a single value to several variables simultaneously.

    a = b = c = 1
    print(a, b, c)
    # Out: 1 1 1
    

    In this case, a, b, and c, are all independent -- changing one will not change the others:

    a = b = c = 1
    print(a, b, c)
    # Out: 1 1 1
    b = 2
    print(a, b, c)
    # Out: 1 2 1
    

    However, note that changing the contents of an object that is referred to by a variable will be reflected through any other variables that reference the same object. That is, if x and y point at the same mutable object(e.g., lists, dictionaries, sets, or byte arrays), changing the contents of one will be seen through the other:

    x = y = [7, 8, 9]   # x and y refer to the same list; i.e., they refer to same memory location
    x = [13, 8, 9]      # now we are assigning a brand new list to x (memory location for x changed!)
    print(y)            # y is unchanged, so it's OK
    # Out: [7, 8, 9]
    

    But:

    x = y = [7, 8, 9]   # x and y refer to the same list i.e. refer to same memory location
    x[0] = 13           # now we are replacing first element of x with 13 (memory location for x unchanged)
    print(y)            # this time y changed!
    # Out: [13, 8, 9]
    

    In plain English:

    x = y = [7, 8, 9]   # creates hardware level bonds between x and y because [7, 8, 9] is a mutable object
    x = y = 7           # does not create any bonds, just assigns because 7 is an immutable object
    

    Nested lists are also valid in python. This means that a list can contain another list as an element.

    x = [1, 2, [3, 4, 5], 6, 7] # this is nested list
    print x[2]
    # Out: [3, 4, 5]
    print x[2][1]
    # Out: 4
    

    Lastly, variables in Python do not have to stay the same type as which they were first defined -- you can simply use = to assign a new value to a variable, even if that value is of a different type.

    a = 2 
    print(a)
    # Out: 2
    
    a = "New value"
    print(a)
    # Out: New value
    
  • 42

    First of all, unlike the other popular programming languages (except CoffeeScript, Haskell etc.), indentation in Python is mandatory. Because indentation's itself seamlessly defines the code blocks and with this Python aims to be more human-readable. Despite that, this rule can cause you some troubles if your code editor is miscalibrated.

    Python uses the colon symbol (:) and indentation for showing where blocks of code begin and end (If you come from another language, do not confuse this with somehow being related to the ternary operator). That is, blocks in Python, such as functions, loops, if clauses and other constructs, have no ending identifiers. All blocks start with a colon and then contain the indented lines below it.

    For example:

    def my_function():    # This is a function definition. Note the colon (:)
        a = 2             # This line belongs to the function because it's indented
        return a          # This line also belongs to the same function
    print(my_function())  # This line is OUTSIDE the function block
    

    or

    if a > b:             # If block starts here
        print(a)          # This is part of the if block
    else:                 # else must be at the same level as if
        print(b)          # This line is part of the else block
    

    Blocks that contain exactly one single-line statement may be put on the same line, though this form is generally not considered good style:

    if a > b: print(a)
    else: print(b)  
    

    Attempting to do this with more than a single statement will not work:

    if x > y: y = x
        print(y) # IndentationError: unexpected indent
    
    if x > y: while y != z: y -= 1  # SyntaxError: invalid syntax
    

    An empty block causes an IndentationError. Use pass (a command that does nothing) when you have a block with no content:

    def will_be_implemented_later():
        pass
    

    It is howewer possible, although most of the time a bad practice, to put several statements on a single line using ;

    For instance:

    print('Hello world'); print('Hello world')
    

    Spaces vs. Tabs

    In short: always use 4 spaces for indentation.

    Using tabs exclusively is possible but PEP 8, the style guide for Python code, states that spaces are preferred.

    Python 3.x3.0

    Python 3 disallows mixing the use of tabs and spaces for indentation. In such case a compile-time error is generated: Inconsistent use of tabs and spaces in indentation and the program will not run.

    Python 2.x2.7

    Python 2 allows mixing tabs and spaces in indentation; this is strongly discouraged. The tab character completes the previous indentation to be a multiple of 8 spaces. Since it is common that editors are configured to show tabs as multiple of 4 spaces, this can cause subtle bugs.

    Citing PEP 8:

    When invoking the Python 2 command line interpreter with the -t option, it issues warnings about code that illegally mixes tabs and spaces. When using -tt these warnings become errors. These options are highly recommended!

    Many editors have "tabs to spaces" configuration. When configuring the editor, one should differentiate between the tab character ('\t') and the Tab key.

    • The tab character should be configured to show 8 spaces, to match the language semantics - at least in cases when (accidental) mixed indentation is possible. Editors can also automatically convert the tab character to spaces.
    • However, it might be helpful to configure the editor so that pressing the Tab key will insert 4 spaces, instead of inserting a tab character.

    Python source code written with a mix of tabs and spaces, or with non-standard number of indentation spaces can be made pep8-conformant using autopep8. (A less powerful alternative comes with most Python installations: reindent.py)

Please consider making a request to improve this example.

Remarks

Python logo
Python
is a widely used programming language. It is:

  • High-level: Python automates low level operations such as memory management. It leaves the programmer with a bit less control, but has many benefits including code readability, and minimal code expressions.

  • General-purpose: Python is built to be used in all contexts and environments. An example for a non-general-purpose language is PHP: it is designed specifically as a server-side web-development scripting language. In contrast, Python can be used for server-side web-development, but also for building desktop applications.

  • Dynamically typed: Every variable in Python can reference any type of data. A single expression may evaluate to data of different types at different times. Due to that, the following code is possible:

    if something:
        x = 1
    else:
        x = 'this is a string'
    print(x)
    
  • Strongly typed: During program execution, you are not allowed to do anything that's incompatible with the type of data you're working with. For example, there are no hidden conversions from strings to numbers; a string made out of digits will never be treated as a number unless you convert it explicitly:

    1 + '1'  # raises an error
    1 + int('1')  # results with 2
    
  • Beginner friendly :): Python's syntax and structure is very intuitive. It is high level and provides constructs intended to enable writing clear programs on both a small and large scale. Python supports multiple programming paradigms, including object-oriented, imperative and functional programming or procedural styles. It has a large and comprehensive standard library and many 3rd party easy to install libraries.

Its design principles are outlined in The Zen of Python.

Currently, there are two major release branches of Python which have some significant differences. Python 2.x is the legacy version, although it still sees widespread use. Python 3.x makes a set of backwards-incompatible changes which aim to reduce feature duplication. For help deciding which version is best for you, see this article.

The official Python documentation is also a comprehensive and useful resource, containing documentation for all versions of Python as well as tutorials to help get you started.

There is one official implementation of the language supplied by Python.org, generally referred to as CPython, and several alternative implementations of the language on other runtime platforms. These include IronPython (running Python on the .NET platform), Jython (on the Java runtime) and PyPy (implementing Python in a subset of itself).

Versions

Python 3.x

VersionRelease Date
3.62016-12-16
3.52015-09-13
3.42014-03-17
3.32012-09-29
3.22011-02-20
3.12009-06-26
3.02008-12-03

Python 2.x

VersionRelease Date
2.72010-07-03
2.62008-10-02
2.52006-09-19
2.42004-11-30
2.32003-07-29
2.22001-12-21
2.12001-04-15
2.02000-10-16
Still have a question about Getting started with Python Language? Ask Question

Topic Outline