Python Guide - Preliminary Understanding Python

zhaozj2021-02-11  249

?

Subdirectory

3.1 Preliminary Understanding Python

3.1.1 Value 3.1.2 String 3.1.3 Unicode String 3.1.4 Link Picture 3.2 Start Programming

? 3. Python's informal introduction

In the following example, the method of distinguishing the input and output is to see if there is a prompt (">>>?" And "..?"): If you want to repeat these examples, you have to enter all after the prompt display. Everything; there is no line starting with a prompt, which is the information output by the interpreter. It should be noted that the slave prompt in the example is used for the end of the multi-line command, indicating that you need to enter an empty line.

Many examples in this manual include comments, and even have some folding in the interaction prompt. The comments in Python are started at the end of the current row until the symbol "#". Note You may appear in a row, or you may follow the space or program code, but do not appear in the string, the # number in the string is only the ##.

Example:

# this is the first comment

Spam = 1 # and this is the second commer

# ... and now a think!

String = "# this is not a comment."

? 3.1 Preliminary understanding Python

Let us test some simple python commands. Start the interpreter then wait for the main prompt ">>>?" (This can't be used for too long).

3.1.1 value

The behavior of the interpreter is like a calculator. You can enter it into an expression, it will return the result. The expression of the expression is easy to understand: , *, / and most languages ​​(such as C or PASCAL), parentheses for packets. E.g:

>>> 2 2

4

>>> # this is a comment

... 2 2

4

>>> 2 2 # and a comment on the Same Line as cot

4

>>> (50-5 * 6) / 4

5

>>> # Integer Division Returns The Floor:

... 7/3

2

>>> 7 / -3

-3

Like C, the equal sign ("=") is used to assign a variable. The assigned value is read-only.

>>> width = 20

>>> HEIGHT = 5 * 9

>>> Width * Height

900

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

>>> x = y = z = 0 # zero x, y and z

>>> X

0

>>> Y

0

>>> Z

0

Python fully supports floating point numbers. When different types of operands are mixed together, the operator converts integers into floating point numbers.

>>> 3 * 3.75 / 1.5

7.5

>>> 7.0 / 2

3.5

The complex is also supported, and the imaginary part is represented by a suffix "j" or "j". The complex number of non-zone is "(Real Imagj)", or can be created via the "Complex (Real, IMAG)" 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)

The complex is always represented by the number of floating point numbers and the virtual portion. The real and imaginary part of the plural z is possible from Z.Real and Z.ImAg.

>>> a = 1.5 0.5J

>>> A.Real

1.5

>>> a.imag

0.5

Functions used to floating point numbers and integer (FLOAT (), int () and long ()) cannot work to multiplexes - there is no way to convert the complex into real numbers. It can be used to obtain its model using ABS (z), or you can get its real part through Z.Real.

>>> a = 3.0 4.0J

>>> Float (a)

TRACEBACK (MOST RECENT CALL LAST):

File "

", LINE 1, IN?"

TypeError: can't Convert Complex to float; use e.g. ABS (z)

>>> A.Real

3.0

>>> a.imag

4.0

>>> ABS (a) # SQRT (A.Real ** 2 a.imag ** 2)

5.0

>>>

In interactive mode, the last expression output is saved in the _ variable. This means that when you use the desktop calculator, it can make continuous calculations, for example:

>>> TAX = 12.5 / 100

>>> price = 100.50

>>> Price * TAX

12.5625

>>> price _ _ _ _

113.0625

>>> Round (_, 2)

113.06

>>>

This variable is read only for users. Don't try to give it a value - Due to Python's grammatical effect, you will only create a partial variable of the same name overwritten it.

3.1.2 String

In addition to values, Python can also operate strings through several different ways. String use single quotes 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.'

>>> '"ISN /' T," SHE SAID. '

'"ISN /' T," SHE SAID. '

Strings can be branched in several ways. It can be used as a continuation in the playback backslash, indicating that the next line is the logic of the current line.

Hello = "this is a rather long string containing / n /

Several Lines of Text Just As You Would Do In C./note That Whitespace At The Beginning of The Line IS /

Significant. "

Print Hello

Note that the wrap / n is represented; the new row mark behind the backslash (NEWLINE, abbreviation "N") will convert to a newline, and the example is printed as follows:

This is a rather long string containing

Several Lines of Text Just As You Would Do IN C.

Note this whitespace at the beginning of the line is significant.

However, if we create a "RAW" line, the / n sequence does not turn into a wrap, the final backslash and the newline n are data processing in the string. As follows:

Hello = R "this is a rather long string containing / n /

Several Lines of Text Much as you would do in c. "

Print Hello

Will print:

This is a rather long string containing / n /

Several Lines of Text Much as you would do in C.

Alternatively, the string can be identified with a pair of triple quotation marks "" "or '' '. The string in the triple quotation marks do not need a wrap tag at the end, and all formats are included in the string.

Print "" "

USAGE: Thingy [Options]

-h Display this usage message

-H hostname hostname to connect

"" "

Products The Following Output:

USAGE: Thingy [Options]

-h Display this usage message

-H hostname hostname to connect

The string printing from the interpreter is identical to the form of them: the internal quotation marks, the quotation marks of the backslash and various strange characters, are precisely displayed. If the string contains single quotes, it does not contain dual quotes, you can use double quotes to reference it, and it can be used in single quotes. (The print statement described later can be used to write a string without quotation marks and backslash).

Strings can be used with number (or bonded), or you can cycle with *.

>>> Word = 'Help' 'A'

>>> Word

'Helpa'

>>> '<' Word * 5 '>'

'

'

The connection between the two string values ​​is automatic. The first line of the previous example can be written as "Word = 'Help' 'A'", which is only valid for the string value, and any string expressions do not apply to this. method.

>>> Import String

>>> 'Str' 'ing' # <- this is ok'string '

>>> String.Strip ('str') 'ing' # <- this is OK

'string'

>>> String.Strip ('str') 'ing' # <- this is invalid

File "

", LINE 1, IN?"

String.strip ('str') 'ing'

^

SyntaxError: Invalid Syntax

The string can be queried by the subscript (index); just like C, the first character of the string is 0. There is no independent character type here, and characters are only a string of one. As in ICON, the string of the string can be represented by a slice flag: two indexes separated by colon.

>>> Word [4]

'A'

>>> Word [0: 2]

'HE'

>>> Word [2: 4]

'lp'

Slice indexing can use default values; omitted the previous index represents 0, omitting the latter index represents the length of the string of the slice.

>>> Word [: 2] # The first two characters

'HE'

>>> Word [2:] # all but the first two characters

'lpa'

Unlike the C string, the Python string cannot be rewritten. Press the string index assignment to generate an error.

>>> Word [0] = 'x'

TRACEBACK (MOST RECENT CALL LAST):

File "

", LINE 1, IN?"

TypeError: Object Doesn't Support Item Assignment

>>> Word [: 1] = 'splat'

TRACEBACK (MOST RECENT CALL LAST):

File "

", LINE 1, IN?"

Typeerror: Object Doesn't Support Slice Assignment

However, a new string can be generated by simple and effective combination:

>>> 'X' Word [1:]

'Xelpa'

>>> 'SPLAT' WORD [4]

'Splata'

Slice operation has a very useful invariance: s [: i] s [i:] is equal to S.

>>> Word [: 2] Word [2:]

'Helpa'

>>> Word [: 3] Word [3:]

'Helpa'

Degraded sliced ​​index is dealt with very beautiful: Excessive index instead of string size, downlink to an empty string than the upper world.

>>> Word [1: 100]

'ELPA'

>>> Word [10:]

'' '

>>> Word [2: 1]

'' '

The index can be a negative number, the count starts from the right, for example: >>> Word [-1] # the last character

'A'

>>> Word [-2] # the last-but-one character

'P'

>>> Word [-2:] # The last two characters

'PA'

>>> Word [: - 2] # all but the last two characters

'HEL'

But -0 is still 0, so it is not counting from the right!

>>> Word [-0] # (SINCE -0 Equals 0)

'H'

The negative slice index of the cross-border is truncated, but don't try to do this in the front element index (non-slice):

>>> Word [-100:]

'Helpa'

>>> Word [-10] # Error

TRACEBACK (MOST RECENT CALL LAST):

File "

", LINE 1, IN?"

IndexError: String Index Out of Range

The best way to understand the slices is the point between the indexes between the two characters. The left side of the first character is 0, and the right side of the nth character in the string is index N, for example:

- - - - -

| H | E | L | P | a |

- - - - -

0 1 2 3 4 5

-5 -4 -3 -2 -1

The first line is the location of the 0 to 5 index given in the string, and the second line is the corresponding negative index. The slice from I to J consists of characters between the two signs.

For non-negative indexes, the length of the slice is the difference in two indexes. For example, the length of WORD [1: 3] is 2.

Built-in function LEN () Returns the length of the string:

>>> s = 'supercalifragilisticexpialidocious'

>>> LEN (S)

34

3.1.3 Unicode string

Starting with Python 2.0, programmers can use a new data type to store text data: Unicode objects. It can be used to store a variety of Unicode data (see http://www.unicode.org/), and, it can be combined with existing string objects by automatic conversion if necessary.

Unicode provides a sequence for all characters in modern and old text. Previously, characters can only use 256 serial numbers, and text usually maps with character mappings by binding code. This is easy to lead to confusion, especially the internationalization of software (INTERNATIONALIZATION - usually writes "I18N" - "I" 18 Characters "N"). Unicode solves this problem by defining a unified code page for all characters.

A Unicode string is defined in Python and define a normal string simple:

>>> U'Hello World! '

U'Hello World! '

The "U" of the quotation marks indicates that the created a Unicode string is created. If you want to join a special character, you can use Python's Unicode-Escape encoding. As shown in the following example: >>> U'Hello / U0020World! '

U'Hello World! '

The replaced / u0020 identifier indicates a Unicode character (spacer) that is inserted into the encoded value of 0x0020 at a given location.

Other characters will also be interpreted directly into a corresponding Unicode code. If you have a Latin-1 encoded string that is commonly used in Western countries, you can find that the first 256 characters of the Unicode character set are exactly the same as the corresponding character coding of the LATION-1.

In addition, there is a row pattern as a normal string. If you want to use Python's Raw-Unicode-Escape encoding, you need to add a UR prefix before quotes of the string. If there may be more than one backslash before lowering "u", it will only convert those separate / uxxx to Unicode characters.

>>> UR'Hello / U0020World! '

U'Hello World! '

>>> UR'Hello // U0020World! '

U'Hellou0020World! '

Row mode is useful when you need to enter a lot of backslashes, which may be used for regular expressions.

As part of these coding criteria, Python provides a complete way to create a Unicode string from known codes.

Built-in functions Unicode () provide access to all registered Unicode encodes for access (encoding and decoding). It converts well-known Latin-1, ASCII, UTF-8, and UTF-16. The two variable length coding characters of the later are set with one or more Byte storage Unicode characters. The default character set is ASCII, which only processes the encoding of 0 to 127, rejects other characters and returns an error. When a Unicode string is printed, it is written or converted by STR (), they are replaced by default encoding.

>>> U "ABC"

U'Abc '

>>> STR (U "ABC")

'ABC'

>>> U "ÄÜ"

u '/ xe4 / xf6 / xfc'

>>> STR (u "Äöü")

TRACEBACK (MOST RECENT CALL LAST):

File "

", LINE 1, IN?"

UnicodeEncodeerror: 'Ascii' Codec Can't Encode Characters in Position 0-2: Ordinal Not in Range (128)

To convert a Unicode character to an 8-bit string with the specified character set, you can use the Encode () method provided by the Unicode object, which has a parameter to specify the encoded name. Code name lowercase.

>>> U "ÄÜ" .Encode ('UTF-8')

'/ xc3 / xa4 / xc3 / xb6 / xc3 / xbc'

If you have a specific encoded string, you want to turn it into a Unicode character set, you can use the UNCODE () function, which is the second parameter as a coded name.

>>> Unicode ('/ XC3 / XA4 / XC3 / XB6 / XC3 / XBC', 'UTF-8')

u '/ xe4 / xf6 / xfc'

3.1.4 Link Picture

Python has several composite data types for organizing other values. The most common is the linked list, which is written to a comma-separated one column (child), and the child of the linked list is not necessarily the value of the same type. >>> a = ['spam', 'Eggs', 100, 1234]

>>> a

['spam', 'Eggs', 100, 1234]

Like a string, the linked list also begins with zero, can be sliced, coupled, and so on:

>>> 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] ['Boe!']

['spam', 'eggs', 100, 'spam', 'eggs', 100, 'spam', 'eggs', 100, 'boe!']

Unlike the constant string, the linked list can change the value of each independent element:

>>> A

['spam', 'Eggs', 100, 1234]

>>> A [2] = a [2] 23

>>> A

['spam', 'Eggs', 123, 1234]

Slice operations can be made, and even change the size of the linked list:

>>> # Replace Some Items:

... a [0: 2] = [1, 12]

>>> A

[1, 12, 123, 1234]

>>> # REMOVE SOME:

... a [0: 2] = []

>>> a

[123, 1234]

>>> # Insert Some:

... a [1: 1] = ['Bletch', 'XYZZY']

>>> a

[123, 'Bletch', 'xyzzy', 1234]

>>> a [: 0] = a # INSERT (a copy of) itself at the beginning

>>> a

[123, 'Bletch', 'XYZZY', 1234, 123, 'Bletch', 'XYZZY', 1234]

The built-in function len () can also be used for linked lists:

>>> LEN (a)

8

It can also nested a list (create another linked list in the linked list), for example:

>>> q = [2, 3]

>>> P = [1, Q, 4]

>>> LEN (P)

3

>>> p [1]

[twenty three]

>>> p [1] [0]

2

>>> p [1] .append ('XTRA') # See section 5.1 >>> P

[1, [2, 3, 'XTRA'], 4]

>>> Q

[2, 3, 'XTRA']

Note that the last example, P [1] and Q actually point the same object! We will tell the object syntax later.

? 3.2 start programming

Of course, we can use Python to add 2 more complex things than 2 plus 2. For example, we can output subsequences of the Fibonacci sequence with the following methods:

>>> # Fibonacci Series:

... # The sum of two elements defines the next

... a, b = 0, 1

>>> While B <10:

... Print B

... a, b = b, A B

...

1

1

2

3

5

8

Some new features are introduced in the example:

The first line includes composite parameters: variables A and B are also assigned 0 and 1. In the last line, this technology has proved to make an operation before the expression before the assignment. The expression on the right is calculated from left to right. The While loop runs in the condition for true time. In Python, it is true, zero is fake similar to any non-zero value. This condition can also be used in strings or linked lists, and the truth is true for any sequence type, the length is not zero, and the null sequence is false. The examples used are a simple comparison. The standard comparison operator is written and C. <(less),> (greater than), == (equal to), <= (less than or equal),> = (greater than or equal) and! = (Not equal). The cyclic body is indent: indentation is a method of python's statement packet. Python still does not provide a smart editing feature so you want to enter a Tab or (one or more) spaces at each shrinkage. In fact, you may prepare a more complex text editor to write your Python program, and most text editors provide automatic indentation. When an interactive input is a complex statement, you need to complete it with a blank line (because the interpreter can't guess when you enter the last line). It should be noted that every line must have the same empty character to identify this is the same statement. The PRINT statement prints the value of a given expression. It is different from you to enter the expression you need (just like the previous calculator example), which can output multiple expressions simultaneously. There is no quotation when the string is output, and the items are separated from one space, you can easily distinguish them, as shown below: >>> i = 256 * 256

>>> Print 'The Value of i is', i

The value of i is 65536 The comma at the end of the Print statement avoids the wrap in the output: >>> a, b = 0, 1

>>> While B <1000:

... Print B,

... a, b = b, A B

...

1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 What should be noted that if the last line is still not written, the interpreter will insert a new line when it prints the next command.

转载请注明原文地址:https://www.9cbs.com/read-4563.html

New Post(0)