# What does

## 3. An informal introduction to Python¶

To try out the following examples, you must type in everything that follows the prompt (or). Lines that do not begin with such a prompt are output from the interpreter. If the secondary prompt is on one line alone, a blank line must be entered. This completes multi-line commands.

Many of the examples in this tutorial contain comments, including those entered in interactive mode. In Python, comments start with a hash and last until the end of the physical line. A comment can begin at the beginning of a line or later in a line, but not within a character string literal. A diamond within a string literal is just a diamond. Since comments are used to explain code and are not interpreted by Python, they can be omitted when typing.

Some examples:

# This is the first comment spam = 1 # and this is the second comment # ... and now a third! String = "# This is not a comment."

### 3.1. Using Python as a calculator¶

Let's try a few simple Python commands: start the interpreter and wait for the primary prompt,.

### 3.1.1. Numbers¶

The interpreter can be used like a pocket calculator: you can enter an expression and the interpreter calculates the result. The syntax for such expressions is simple: the operators,, and work just like in most other languages ​​(e.g. Pascal or C); Brackets can be used for grouping. For example:

>>> 2 + 24 >>> # This is a comment ... 2 + 24 >>> 2 + 2 # and this is a comment on the same line as Code4 >>> (50-5 * 6) /45.0> >> 8/5 # Fractions are not lost when dividing integers 1.6

Note: The last calculation may not give you exactly the same result because results of floating point calculations can differ from computer to computer. In the further course it will be discussed how you can define the representation for the output of floating point numbers. See Floating Point Arithmetic: Problems and Limitations for a detailed discussion of some of the intricacies of floating point numbers and their representation.

To perform an integer division that returns an integer result and neglects the fraction of the result, there is the operator:

>>> # Integer division returns a rounded result: ... 7 // 32 >>> 7 // - 3-3

The equal sign () is used to assign a value to a variable. After that, no result will be displayed before the next interactive prompt:

>>> width = 20 >>> height = 5 * 9 >>> width * height900

A value can be assigned to several variables at the same time:

>>> x = y = z = 0 # zero for x, y and z >>> x0 >>> y0 >>> z0

Variables must be “defined” before they can be used, otherwise an error will occur. This definition is done through an assignment:

>>> # Try to get an undefined variable ... nTraceback (most recent call last): File "", line 1, in NameError: name 'n' is not defined

Python has full support for floating point numbers. If operands of different number types are linked by an operator, then integer operands are converted into floating point numbers:

>>> 3*3.75/1.57.5>>> 7.0/23.5

Complex numbers are also supported. The imaginary part is given with the suffix or. Complex numbers with a real part other than zero are written as or can be generated with the function.

>>> 1j * 1J (-1 + 0j) >>> 1j * complex (0,1) (- 1 + 0j) >>> 3 + 1j * 3 (3 + 3j) >>> (3 + 1j) * 3 (9 + 3j) >>> (1 + 2j) / (1 + 1j) (1.5 + 0.5j)

Complex numbers are always represented by two floating point numbers, the real part and the imaginary part. To these parts of a complex number z to select, are and available.

>>> a = 1.5 + 0.5j >>> a.real1.5 >>> a.imag0.5

The conversion functions to floating point numbers and integers (,) are not available for complex numbers. One can use to calculate the absolute value of a complex number (as a floating point number), or to get the real part:

>>> a = 3.0 + 4.0j >>> float (a) Traceback (most recent call last): File "", line 1, in? TypeError: can't convert complex to float; use abs (z) >>> a.real3.0 >>> a.imag4.0 >>> abs (a) # sqrt (a.real ** 2 + a.imag ** 2) 5.0 >>>

In interactive mode, the last expression output is assigned to the variable. This is particularly helpful when using the Python interpreter as a calculator

>>> tax = 12.5 / 100 >>> price = 100.50 >>> price * tax12.5625 >>> price + _113.0625 >>> round (_, 2) 113.06 >>>

The variable should be treated as if it were read-only and should not be explicitly assigned a value. This would create an independent local variable with the same name that obscures the built-in variable with its special behavior.

### 3.1.2. Strings ¶

In addition to numbers, Python can also handle strings that can be represented in different ways. They can be enclosed in single or double quotes:

>>> 'spam eggs''spam eggs' >>> 'doesn \' t '"doesn't" >>> "doesn't" "doesn't" >>>' "Yes," he said . '' "Yes," he said. '>>> "\" Yes, \ "he said."' "Yes," he said. '>>>' "Don't eat it \ ', "she said." "Don't eat it," she said.

The interpreter outputs the result of string operations in the same way as they are entered: inside quotation marks and with quotation marks escaped with backslashes or other strange characters to reflect the exact value. The string is enclosed in double quotation marks if it contains a single quotation mark but no double quotation marks, otherwise it is enclosed in single quotation marks. The function produces a more readable output.

There are several ways to create multi-line character string literals, for example using continuation lines that indicate with a backslash at the end of the physical line that the next line is the logical continuation of the current one:

hello = "This is a rather long character string \ n \ that contains several lines of text and how it would be written in C. \ n \ Attention: Spaces at the beginning \ have a meaning for the display." print (hello)

It should be noted that line breaks must still be embedded in the character string with the help of. However, the line break following the backslash does not belong to the character string. The output generated by the example looks like this:

This is a fairly long string that contains several lines of text and is just as you would write it in C. Attention: Spaces at the beginning have a meaning for the representation.

Strings can also be surrounded by a pair of triple quotation marks: or. Line ends do not have to be escaped, but are included in the character string. Therefore, in the following example, the first line end is escaped to avoid the undesired leading blank line:

print ("" "\ Usage: thingy [OPTIONS] -h Display this usage message -H hostname hostname to connect to" "")

This produces the following output:

Usage: thingy [OPTIONS] -h Display this usage message -H hostname Hostname to connect to

If we make the string literal a “raw” string, it will not be converted to a newline; The backslash at the end and the line break in the source code are also part of the string. The example:

hello = r "This is a fairly long string \ n \ that contains several lines of text and just as you would write it in C." print (hello)

This is a fairly long string \ n \ that contains several lines of text, just as you would write it in C.

Strings can be concatenated with the operator and repeated with:

>>> word = 'Help' + 'A' >>> word'HelpA '>>>' <'+ word * 5 +'> '' '

Two character string literals next to each other are automatically linked with one another. The first line in the example above could also have read. However, this only works with two literals, not with arbitrary string expressions:

>>> 'str''ing' # this is ok'string '>>>' str'.strip () + 'ing' # this is ok'string '>>>' str'.strip () 'ing' #This is invalid file "", line 1, in? 'str'.strip ()' ing '^ SyntaxError: invalid syntax

Strings can be indexed, whereby the first character of a string has the index 0 as in C (“zero-based counting”). There is no special character type (as in C) - a character is simply a string of length one. As in the Icon programming language, parts of a character string can be entered using Slice notation (Cut-out notation). Two indices are specified, separated by a colon ().

>>> word [4] 'A' >>> word [0: 2] 'He' >>> word [2: 4] 'lp'

Slice indexes have useful default values: if the first index is omitted, the segment begins with the first character of the string (index 0), if the second index is omitted, the segment extends to the end of the string

>>> word [: 2] # The first two characters 'He' >>> word [2:] # Everything except the first two characters 'lpA'

In contrast to a C string, a Python string cannot be changed - character strings are unchangeable (immutable). Attempting to assign something to an indexed position of a character string leads to an error message

>>> word [0] = 'x'Traceback (most recent call last): File "", line 1, in? TypeError:' str 'object does not support item assignment >>> word [: 1] = 'Splat'Traceback (most recent call last): File "", line 1, in? TypeError:' str 'object does not support slice assignment

Instead, you simply create a new string with the combined content

>>> 'x' + word [1:] 'xelpA' >>> 'Splat' + word [4] 'SplatA'

Another example: corresponds.

>>> word [: 2] + word [2:] 'HelpA' >>> word [: 3] + word [3:] 'HelpA'

If indices are specified in the slice notation that exceed the actual length of a character string, this does not lead to an error message: If the second index is too large, it is replaced by the length of the character string and sections that do not contain any characters return an empty character string.

>>> word [1: 100] 'elpA' >>> word [10:] '' >>> word [2: 1] ''

Indices can also be negative numbers - then counting from right to left. For example:

>>> word [-1] # The last character'A '>>> word [-2] # The penultimate character' p '>>> word [-2:] # The last two characters' pA' >>> word [: - 2] # Everything but the last two characters 'Hel'

Attention: -0 is the same as 0. This means that counting starts normally from the left!

>>> word [-0] # (since -0 equals 0) 'H'

The automatic shortening when using indices that are outside the actual length of the character string only works with the slice notation, not when accessing a single character using the index notation:

>>> word [-100:] 'HelpA' >>> word [-10] # Error Traceback (most recent call last): File "", line 1, in? IndexError: string index out of range

When slicing the indices can be thought of as between the characters - where the left corner of the first character has the index 0 and the right corner of the last character has one n Character long string the index n. An example

+ --- + --- + --- + --- + --- + | H | e | l | p | A | + --- + --- + --- + --- + - - + 012345-5-4-3-2-1

The first row of numbers indicates the position of the indices 0 ... 5 in the string, the second row the corresponding negative indices. The excerpt from i to j consists of all the characters between the positions that go through i respectively j be marked.

When using non-negative indices, the length of the segment defined by this corresponds to the difference between the two indices, provided both are within the actual limits of the character string. For example, the length of is 2.

The built-in function returns the length of a string:

>>> s = 'supercalifragilisticexpialidocious' >>> len (s) 34

Sequence types
Strings belong to the Sequence types and have all of the operations supported by these types.
String Methods
Strings have a large number of methods for basic transformation and search.
String formatting
Information on formatting strings with can be found here.
Old String Formatting Operations
The old formatting operations called when strings and unicode strings are the left operands of the operator are described in detail here.

Starting with Python 3.0, all strings support Unicode.

Unicode has the advantage that it provides an ordinal number for every character in every document used in modern and ancient texts. Before that, only 256 ordinal numbers were possible for characters. Texts were typically bound to a code page that assigned the ordinal numbers to the characters. This led to a lot of confusion, especially with regard to the internationalization of software (usually - + 18 characters +). Unicode solves these problems by defining a code page for all characters.

If you want to include special characters in a character string, you can do this by using Pythons Unicode escape- notation. The following example shows how:

>>> 'Hello \ u0020World!' 'Hello World!'

The escape sequence indicates that the Unicode character with the ordinal number 0x0020 (the space) should be inserted at the given position.

Other characters are interpreted using their respective ordinal numbers directly as Unicode ordinal numbers. If you have character string literals in the normal Latin-1 encoding, which is used in many Western countries, then the first 256 characters of Unicode correspond to the same characters of the Latin-1 encoding.

In addition to these standard encodings, Python provides a whole range of other options for creating Unicode strings, provided you know the encoding used.

To convert character strings into byte sequences, string objects provide the method that accepts the name of the coding as an argument, preferably in lowercase letters.

>>> "Apples" .encode ('utf-8') b '\ xc3 \ x84pfel'

### 3.1.4. Listen¶

Python knows many compound data types (compound data types) that can be used to group different values. The most flexible of these is the list (list): A list of values ​​(elements) separated by commas and enclosed in square brackets. List items do not all have to be of the same type.

>>> a = ['spam', 'eggs', 100,1234] >>> a ['spam', 'eggs', 100, 1234]

Like the indexing of character strings, the list indexing is also zero-based - the first element therefore has the index 0. The slicing known from character strings as well as the concatenation and multiplication or are possible with lists

>>> a [0] 'spam' >>> a [3] 1234 >>> a [-2] 100 >>> a [1: -1] ['eggs', 100] >>> a [: 2] + ['bacon', 2 * 2] ['spam', 'eggs',' bacon ', 4] >>> 3 * a [: 3] + [' Boo! '] [' Spam ',' eggs', 100, 'spam', 'eggs', 100,' spam ',' eggs', 100, 'Boo!']

All slicing operations return a new list that contains the requested items. This means that the following operation will make a shallow copy (shallow copy) of the list returns:

>>> a [:] ['spam', 'eggs', 100, 1234]

In contrast to strings, however, lists are changeable (mutable) so that it is possible to make changes within a list

>>> a ['spam', 'eggs', 100, 1234] >>> a [2] = a [2] +23 >>> a ['spam', 'eggs', 123, 1234]

Even assignments to slices are possible. This allows you to change the length of a list or even empty it entirely

>>> # Replace a few elements: ... a [0: 2] = [1,12] >>> a [1, 12, 123, 1234] >>> # Remove a few: ... a [ 0: 2] = [] >>> a [123, 1234] >>> # Insert a couple: ...a [1: 1] = ['bletch', 'xyzzy'] >>> a [123, 'bletch', 'xyzzy', 1234] >>> # (a copy of) insert yourself at the beginning: >> > a [: 0] = a >>> a [123, 'bletch', 'xyzzy', 1234, 123, 'bletch', 'xyzzy', 1234] >>> # Empty the list: All elements with an empty space Replace list >>> a [:] = [] >>> a []

The built-in function can also be used on lists:

>>> a = ['a', 'b', 'c', 'd'] >>> len (a) 4

It is also possible to nest lists (nest), that is, to create lists that contain other lists. An example:

>>> q = [2,3] >>> p = [1, q, 4] >>> len (p) 3 >>> p [1] [2, 3] >>> p [1] [ 0] 2

You can also add something to the end of a list:

>>> p [1] .append ('xtra') >>> p [1, [2, 3, 'xtra'], 4] >>> q [2, 3, 'xtra']

Note that in the last example and really point to the same object! We'll come to the later Object semantics back.

### 3.2. First steps in programming¶

Of course, you can use Python for more complicated tasks than just adding two and two. For example, the first links of the Fibonacci sequence generate as follows:

>>> # Fibonacci sequence: ... # The sum of the last two elements results in the next ... a, b = 0.1 >>> whileb <10: ... print (b) ... a, b = b, a + b ... 112358

This example introduces a couple of new properties.

• The first line contains a Multiple assignment (multiple assignment): The variables and get the new values ​​0 and 1 at the same time. In the last line it is inserted again to show that all expressions on the right side are evaluated first before any assignment is made! The expressions on the right are evaluated from left to right.

• The loop is executed as long as the condition (here:) is true. In Python, as in C, any non-zero number is true (True), Zero is false (False). The condition can also be a string or list value, actually any sequence. Anything with a length other than zero is true, empty sequences are untrue. The condition in the example is a simple comparison. The normal comparison operators are written as in C: (less than), (greater than), (equal to), (less than or equal to), (greater than or equal to) and (not equal to).

• The Loop body is indented (indented): Indentation is used to group in Python. In the interactive prompt you have to enter tabs or spaces for each indented line. In practice, you will prepare more complicated pieces of code with a text editor, and all reasonable editors will have a way to automatically indent. If a compound statement (compound statement) is entered interactively, it must be followed by a blank line to indicate that it is complete, as the parser cannot guess when the last line has been entered. Note that every line in a block that belongs together must be indented the same way.

• The function outputs the value of the expression that was passed to it. The output for multiple expressions, floating point numbers, and strings differs from the output that is obtained when simply entering the expressions (as we did earlier in the calculator examples). Strings are output without quotation marks, and if more than one argument is specified, a space is inserted between each argument. Simple formatting can thus be carried out, as the example shows

>>> i = 256 * 256 >>> print ('The value of i is', i) The value of i is 65536

Using the keyword argument end the line break after the output can be prevented or the output can be terminated with a different string.

>>> a, b = 0,1 >>> whileb <1000: ... print (b, end = '') ... a, b = b, a + b ... 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987