Python Language


This draft deletes the entire topic.

expand all collapse all

Examples

  • 196

    Python is a high-level, structured, open-source, dynamically typed programming language that can be used for a wide variety of 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. Note that many projects still use Python 2 because transitioning is difficult.
    • Python 3.x is the current version and is under active development.

    You can download and install the latest version of Python 2 or 3 here. See Python 2 vs. Python 3 for a comparison of the differences between Python 2 and 3. In addition, some 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 analysis or scientific use. See the list at the official site.

    Hello World Python file

    Create a new file hello.py that contains the following line:

    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.

    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'
    

    Hello, World in Python using IDLE

    IDLE is a simple editor for Python, that comes bundled with Python.

    How to create 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.

    A prompt of three right angle brackets should appear:

    >>>
    

    Now write the following code in the prompt:

    >>> print("Hello, World")
    

    Hit Enter

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

    The main purposes of the IDLE are:

    • Multi-window text editor with syntax highlighting, autocompletion, and smart indent
    • Python shell with syntax highlighting
    • Integrated debugger with stepping, persistent breakpoints, and call stack visibility
    • Automatic indentation (useful for beginners learning about Python's indentation)
    • Saving 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:

    $ 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 command 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 (running) the python command in your terminal, you are presented with an interactive Python shell (also known as a REPL)

    $ 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 an interactive Python shell online.

    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 and edit/execute them as scripts or programs with external tools e.g. shell, IDEs (such as PyCharm), Jupyter notebooks, etc. Intermediate users may use these tools; however, the methods discussed here are sufficient for getting started.

    PEP8 defines guidelines for formatting Python code. Formatting code well is important so you can quickly read what the code does.

  • 76

    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.

    The following paragraph only applies to programmers that have previously used a statically typed language.

    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. You can't declare a variable without assigning it an initial value. You do not need to allocate memory.

    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
    

    Python automatically assigns the appropriate type to a variable.

    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'>
    

    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
    

    In other words, python variables are references.

    Nested lists are 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
    
  • 45

    Unlike many other programming languages, indentation in Python is mandatory. Indentation seamlessly defines code blocks for the purpose of code readability. However, 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 lines indented 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, however, 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

    tl;dr: 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 4 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.

    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.

  • 17

    IDLE is Python’s Integrated Development and Learning Environment and is an alternative to the command line. As the name may imply, IDLE is very useful for developing new code or learning python. On Windows this comes with the Python interpreter, but in other operating systems you may need to install it through your package manager.

    In IDLE, hit F5 or run Python Shell to launch an interpreter. Using IDLE can be a better learning experience for new users because code is interpreted as the user writes.

    Troubleshooting

    • Windows

      If you're on Windows, the default command is python. If you receive a "'python' is not recognized" error, the most likely cause is that Python's location is not in your system's PATH environment variable. This can be accessed by right-clicking on 'My Computer' and selecting 'Properties' or by navigating to 'System' through 'Control Panel'. Click on 'Advanced system settings' and then 'Environment Variables...'. Edit the PATH variable to include the directory of your Python installation, as well as the Script folder (usually C:\Python27;C:\Python27\Scripts). This requires administrative privileges and may require a restart.

      When using multiple versions of Python on the same machine, a possible solution is to rename one of the python.exe files. For example, naming one version python27.exe would cause python27 to become the Python command for that version.

      You can also use the Python Launcher for Windows, which is available through the installer and comes by default. It allows you to select the version of Python to run by using py -[x.y] instead of python[x.y]. You can use the latest version of Python 2 by running scripts with py -2 and the latest version of Python 3 by running scripts with py -3.

    • Debian/Ubuntu/MacOS

      This section assumes that the location of the python executable has been added to the PATH environment variable.

      If you're on Debian/Ubuntu/MacOS, open the terminal and type python for Python 2.x or python3 for Python 3.x.

      Type which python to see which Python interpreter will be used.

    • Arch Linux

      The default Python on Arch Linux (and descendants) is Python 3, so use python or python3 for Python 3.x and python2 for Python 2.x.

    • Other systems

      Python 3 is sometimes bound to python instead of python3. To use Python 2 on these systems where it is installed, you can use python2.

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-23
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