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.
3.1. Using Python as a calculator¶
Let's try a few simple Python commands: start the interpreter and wait for the primary prompt,.
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:
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:
The equal sign () is used to assign a value to a variable. After that, no result will be displayed before the next interactive prompt:
A value can be assigned to several variables at the same time:
Variables must be “defined” before they can be used, otherwise an error will occur. This definition is done through an assignment:
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:
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.
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.
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:
In interactive mode, the last expression output is assigned to the variable. This is particularly helpful when using the Python interpreter as a calculator
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:
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:
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:
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:
This produces the following output:
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:
leads to the following output:
Strings can be concatenated with the operator and repeated with:
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:
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 ().
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
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
Instead, you simply create a new string with the combined content
Another example: corresponds.
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.
Indices can also be negative numbers - then counting from right to left. For example:
Attention: -0 is the same as 0. This means that counting starts normally from the left!
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:
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
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:
- 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.
3.1.3. About Unicode¶
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:
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.
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.
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
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:
In contrast to strings, however, lists are changeable (mutable) so that it is possible to make changes within a list
Even assignments to slices are possible. This allows you to change the length of a list or even empty it entirely
The built-in function can also be used on lists:
It is also possible to nest lists (nest), that is, to create lists that contain other lists. An example:
You can also add something to the end of a list:
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:
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.
© Copyright 2010 - 2013, Michael Markert et al. Revision.
- What are the domain names
- Where did the Polynesian people come from?
- What is the Most Popular Casino Game?
- Is China now officially a military dictatorship?
- How does a write-back cache work
- Why is anemia linked to constipation
- How is money made with prisoners
- Anti-gravity is a theoretical possibility
- What's after a quarter of meth
- How strong was the Byzantine Empire
- How accurate is the TV series Scorpion
- How Much Whey Protein Should You Ingest?
- What do Thai people think of Chinese tourists?
- Penicillin is an antibody
- Where can someone learn MS Excel
- Dropshipping is an outdated business model
- How are gravitational waves recorded
- Will India ever overtake China?
- Shared web hosting is SEO friendly
- Which country does Sonia Gandhi come from
- Where can I learn Mandarin in Delhi
- The damage caused by unhealthy foods is permanent
- What percentage of soldiers died in the First World War?
- How do I make a diet