Python tutorial (3): an informal introduction to Python

Source: Internet
Author: User
Tags integer division
Document directory
  • 3.1.1 numbers
  • 3.1.2 string
  • 3.1.3 about Unicode
  • 3.1.4 list

In the following example, the input and output are distinguished by a prompt (>>> and. To redo the example, after the prompt appears, all the input content must be followed by the prompt. All rows that do not start with a prompt are output from the interpreter. If a row has only one second prompt, it means you must enter a blank line, which is used to end a multi-line command.

This Manual contains many examples and comments. The comment starts with the # character in Python until the end of the line. The comment can appear at the beginning of a line, or be followed by spaces and code, not in the string literal value. The # character in the string literal value is a # character. Because annotations make the code clearer and are not explained by python, You can omit them when you redo these examples.

Some examples:

3.1 Use python as a calculator

Let's try some simple Python commands. Start the interpreter and wait for the primary prompt (>>> ).

3.1.1 numbers

The interpreter is like a calculator. You can enter an expression that calculates the value. The expression syntax is straightforward. The operator +-*/is the same as that in most other languages. Brackets can be used for grouping. For example:

Note: You may not see this result. Floating Point Numbers may have different results on different machines. Later, we will introduce more information about controlling the display of floating point output.

To realize integer division, discard the decimal part and obtain the integer result, use another operator //:

Equal sign (=) is used to assign a value to a variable, and no result is displayed before the next prompt:

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

Variables must be defined (assigned to a value) before use; otherwise, an error occurs:

The operator fully supports floating-point operations. When the operands of the mixed type appear at the same time, the integer type will be converted to the floating point type:

The plural value is also supported. The imaginary part carries a suffix J or J, and a plural value with a non-zero real part is represented as (Real + imagj), or is created as a complex (Real, IMAG) function.

The plural is always expressed as two floating point numbers, real and virtual. The two parts are extracted from the Plural Z using Z. Real and Z. imag.

The floating-point and Integer Conversion functions are not applicable to the complex numbers. It is not correct to convert a complex number into a real number. Use ABS (z) to obtain its quantity value or Z. Real to obtain its real part:

In interactive mode, the value of the last printed expression is assigned to _ (underline ). This means that when you use python as a desktop calculator, it makes it easier to continue computing, for example:

This variable should be read-only. Do not explicitly assign values to it. You can create a local variable with the same name to cover the built-in variables and their magic actions.

3.1.2 string

In addition to numbers, python can also operate strings in several forms. It can be enclosed in single or double quotation marks:

The interpreter prints the result of the string operation in the same way as the input, including quotation marks and other interesting characters escaped by the backslash to display the exact value. If a string contains single quotation marks but not double quotation marks, the string will be included in double quotation marks. On the contrary, it will be included in single quotation marks. The print () function generates a more readable output for these input strings.

The string literal value can span multiple rows in several ways. The row to be continued can be used. A backslash is added at the end of the row to indicate that the next row is logically continued:

Note: The new line still needs to be embedded into the string. If \ n is used, the new line following the backslash at the end of the line will be discarded (the line break generated when you press Enter ). Sample output:

Or a string can be enclosed by a pair of matching three quotation marks, "Or ''' (three double quotation marks or single quotation marks). The line terminator does not need to be escaped, but they will be contained in strings. The following example uses an escape to avoid an undesired initial blank line.

Generate the following output:

If we use the string literal value as the "original" string, \ n will not be converted to a new line, the backslash at the end of the line, and the linefeed will be included in the string as data. Therefore, for example:

Will print out:

Strings can be connected using +, and * can be repeated:

The literal values of two adjacent strings are automatically connected. The first line in the preceding example can also be written as word = 'help' 'A'. It takes effect only when two strings are called, no other string expressions are supported:

A string can be indexed by subscript. The subscript of the first character is 0. There is no separate character type. A character is a string of the same length. Just as in the graphic character programming language, you can specify the two indexes separated by colons by using the label of slices.

Slice indexes have useful default values. When the first index is ignored, the default value is 0. When the second index is ignored, the default value is the length of the string.

The Python string cannot be changed. Assigning a value to a specified index causes an error:

However, using the Union content to create a string is simple and effective:

This is a useful and unchanged slice operation. s [: I] + s [I:] is equal to S.

An abnormal slice index can be well processed. If an index is too large to be replaced with the length of a string, if the upper bound is smaller than the lower bound, an empty string is returned.

The index can be a negative number. In this way, the count starts from the right side. For example:

But-0 is actually 0, so it does not count from the right.

Negative slice indexes that are out of range will be truncated, but this is wrong when there is only one element (non-slice) index:

One way to remember how slice works is to regard the index as a point in the character, and the left edge of the first character is marked as a number 0, the right edge of the last character of a string of N has an index of N, for example:

The number in the first row gives the position of index 0 .. 5 in the string. The second row provides the corresponding negative index. The slice from I to J consists of all characters marked between I and j edge.

For non-negative indexes, the slice length is the index difference if they are within the boundary. For example, the length of word [1: 3] is 2.

The built-in function Len () returns the string length:

3.1.3 about Unicode

From python3.0, all strings support Unicode.

The advantage of Unicode is that it provides an ordinal number for each text character in each current script and in the past. Previously, there were only 256 possible ordinal numbers for script characters. The text is bounded by a code page, which maps the ordinal number to the script character. This leads to a lot of chaos, especially when it comes to internationalization of software. Unicode solves these problems by defining only one code page for all scripts.

If you want to include a special character in a string, you can use the Unicode escape code of python to complete it. The following example shows how to do this:

Escape Sequence \ u0020 indicates that a Unicode character is inserted at the specified position, and its ordinal value is 0x0020 (Space ).

Other characters use their respective ordinal values as Unicode ordinal values for interpretation. If you have some string literal values that are encoded using Latin-1 in many Western countries, you will find it very convenient, this is because Unicode contains 256 characters lower than Latin-1.

In addition to these standard encodings, Python provides a complete set of other methods for creating Unicode strings based on a known encoding.

Converts a string to a byte sequence using the specified encoding. The String object provides an encode () method with a parameter, which is the name of the encoding. It is best to use lower-case letters for encoding names.

3.1.4 list

Python has many Composite data types used to group other values. The list is used most. It can be expressed as a comma-separated item written in brackets. The items in the list do not need to be of the same type.

Like the index of a string, the index of a list starts from 0 and can be sliced or connected:

All slice operations return a new list containing request elements. This means that the following slice returns a shortest copy of list:

The value of a string cannot be changed. The difference is that the list elements can be changed individually:

You can also assign values to a slice so that you can change the length of the list or clear it as a whole:

Built-in Len () functions also apply to the list:

The list can be nested (The list contains other lists), for example:

You can add elements at the end of the list:

Note: In the last example, P [1] and q reference the same object.

3.2 The first step towards programming

Of course, we can use python to complete more complex tasks than adding two things. For example, we can initialize a Fibonacci series. As follows:

This example contains several new features.

  • The first row contains one or more values. variables A and B both obtain the new values 0 and 1. The last row is used again to demonstrate that all the expressions on the right before any value assignment operation are calculated first. The expression on the right is calculated from left to right.

  • As long as the condition (here B <10) is still true, the while loop is executed. In python, like the C language, a non-zero integer is true, and zero is false. The condition can also be a string or list. In fact, for any sequence, it is true as long as the length is not zero, and the null sequence is false. The test in the example is a simple comparison. The Writing Method of the standard comparison operator is the same as that in C. <(smaller than)> (greater than) = (equal to) <= (less than or equal to)> = (greater than or equal )! = (Not equal ).

  • The body of the loop is indented, and indented is the way python uses grouping statements. At the interactive prompt, you have to enter a tab or several spaces for the contraction. In practice, you need a text editor to prepare more complex input. All the better text editors have the automatic indent function. When a compound statement is input interactively, it must be followed by an empty line (because the parser cannot guess when you enter the last line ). Remember, each line in a basic block must be indented to the same number.

  • The value of the expression passed to the print () function output. It is different from the method you want to output expressions. It processes multiple expressions, floating point numbers, and strings. String output does not contain quotation marks, but contains spaces between characters. You can properly format the string. Like this:

    The keyword end can be used to avoid new rows after the output, or end the output with a different string:

This article is the official website content translation, original address: http://docs.python.org/3/tutorial/introduction.html

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.