{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "\n# What is Python?\n\nThis section will give a very brief introduction to the Python language.\n\n.. tip::\n\n See also the [Python home page](https://www.python.org/) for further\n information.\n\n# Executing Python code\nYou can execute Python code interactively by starting the interpreter like with\nthe command ``python3`` and test it with any python command such as:\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "print('hello')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "You can also put the ``print(\"hello\")`` line in a file (``hello.py``) and\nexecute it as a Python script with ``python3 hello.py`` or ``python3 -i\nhello.py`` to enter interactive mode after the file is executed.\n\nFinally, you can put ``#!/usr/bin/env python3`` in the first line of the\n``hello.py`` file, make it executable (``chmod +x hello.py``) and execute it\nlike any other executable.\n\n\n\n.. tip::\n\n For a better interactive experience, consider ipython.\n\n# Types\n\n.. list-table:: Supported Python Types\n :header-rows: 1\n :widths: 15 30 30\n\n * - **Type**\n - **Description**\n - **Example**\n * - ``bool``\n - Boolean\n - ``False``\n * - ``int``\n - Integer\n - ``117``\n * - ``float``\n - Floating point number\n - ``1.78``\n * - ``complex``\n - Complex number\n - ``0.5 + 2.0j``\n * - ``str``\n - String\n - ``'abc'``\n * - ``tuple``\n - Tuple\n - ``(1, 'hmm', 2.0)``\n * - ``list``\n - List\n - ``[1, 'hmm', 2.0]``\n * - ``dict``\n - Dictionary\n - ``{'a': 7.0, 23: True}``\n\nA dict object is mapping from keys to values:\n\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "d = {'s': 0, 'p': 1}\nd['d'] = 2\nprint('the whole dictionary:', d)\nprint('one entry of the dictionary:', d['p'])" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "In this example all keys are strings and all values are integers. Types can\nbe freely mixed in the same dictionary; any type can be used as a value and\nmost types can be used as keys (mutable objects cannot be keys).\n\nA ``list`` object is an ordered collection of arbitrary objects:\n\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "l = [1, ('gg', 7), 'hmm', 1.2]\nprint('the whole list:', l)\nprint('one list element:', l[1])\nprint('negative index:', l[-2])" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Indexing a list with negative numbers counts from the end of the list, so\nelement ``-2`` is the second last.\n\nA tuple behaves like a list -- except that it can\u2019t be modified in place.\nObjects of types list and dict are mutable -- all the other types listed in\nthe table are immutable, which means that once an object has been created, it\ncan not change. Tuples can therefore be used as dictionary keys, lists\ncannot.\n\n

Note

List and dictionary objects can change. Variables in Python are references\n to objects -- think of the ``=`` operator as a \u201cnaming operator\u201d, not as\n an assignment operator. This is demonstrated here:

\n\n\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "a = ['q', 'w']\nb = a\na.append('e')\nprint('the original, changed list:', a)\nprint('the second list:', b)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The line ``b = a`` gives a new name to the array, and both names now refer to\nthe same list.\n\nHowever, often a new object is created and named at the same time, in this\nexample the number ``42`` is not modified, a new number ``47`` is created and\ngiven the name ``d``. And later, ``e`` is a name for the number ``47``, but\nthen a new number ``48`` is created, and ``e`` now refers to that number:\n\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "c = 42\nd = c + 5\nprint('the first number:', c)\nprint('the second number:', d)\n\ne = d\ne += 1\nprint('second and third number:', (d, e))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "

Note

Another very important type is the ``ndarray`` type described here:\n [Numeric arrays in Python](https://ase-lib.org/numpy.html#numpy). It is\n an array type for efficient numerics, and is heavily used in ASE.

\n\n# Loops\nA loop in Python can be done like this:\n\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "things = ['a', 7]\nfor x in things:\n print(x)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The ``things`` object could be any sequence. Strings, tuples, lists,\ndictionaries, ndarrays and files are sequences. Try looping over some of\nthese types.\n\nOften you need to loop over a range of numbers:\n\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "for i in range(5):\n print(i, i * i)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Functions and classes\n\nA function is defined like this:\n\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "def f(x, m=2, n=1):\n y = x + n\n return y**m\n\n\nprint(f(5))\nprint(f(5, n=8))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Here ``f`` is a function, ``x`` is an argument, ``m`` and ``n`` are keywords\nwith default values ``2`` and ``1`` and ``y`` is a variable.\n\nA class is defined like this:\n\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "class A:\n def __init__(self, b):\n self.c = b\n\n def m(self, x):\n return self.c * x\n\n def get_c(self):\n return self.c" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "You can think of a class as a template for creating user defined objects. The\n``__init__()`` function is called a constructor, it is being called when\nobjects of this type are being created.\n\nIn the class ``A`` ``__init__`` is a constructor, ``c`` is an attribute and\n``m`` and ``get_c`` are methods.\n\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "a = A(7)\nprint(a.c)\nprint(a.get_c())\nprint(a.m(3))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Here we make an instance (or object) ``a`` of type ``A``.\n\n# Importing modules\n\nThere are several ways to import modules (either ``.py`` files in your\nworking directory or packages that are installed in your python environment).\nFor example:\n\n::\n\n import numpy; numpy.linspace(1, 10, num=5)\n\nand\n\n::\n\n import numpy as np; np.linspace(1, 10, num=5)\n\nand\n\n::\n\n from numpy import linspace; linspace(1, 10, num=5)\n\nall yield the same result.\n\n" ] } ], "metadata": { "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.13.7" } }, "nbformat": 4, "nbformat_minor": 0 }