Python programming (2)

zhaozj2021-02-08  197

Chapter III Basic Use

Let's use an example to introduce the basic usage of Python. In the example, the user input and system output have no prompts (>> and ...). If you want to try these examples, you need to type all the commands after prompt, and the rows that are not prompted in the example are the output of the system. Note that only the line of tips will need to type an empty line, which is used to end multi-line commands.

3.1 Use Python as a calculator

Start the interpreter, wait for the main prompt >>>. The interpreter can be used as a calculator. Type an expression and explain the program to output the result. The expression of the expression is very intuitive: , *, /,%, ** and other operators and other languages ​​(such as PASCAL or C) have no difference, parentheses can be used to combine. E.g:

>>> 2 2

4

>>> # This is a comment

... 2 2

4

>>> 2 2 # and code in the same line

4

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

5

>>> # 整 除 除 法 法 法 整 下

... 7/3

2

>>> 7 / -3

-3

>>>

As in C, equal to the number to assign a value to the variable, the result of assigning the value is not displayed:

>>> width = 20

>>> HEIGHT = 5 * 9

>>> Width * Height

900

>>>

You can give a few variables at the same time:

>>> x = y = z = 0 # 把 零 零 零 零 零

>>> X

0

>>> Y

0

>>> Z

0

>>>

Python fully supports floating point numbers, and mixed types of calculations will convert integers to floating point numbers:

>>> 4 * 2.5 / 3.3

3.0303030303

>>> 7.0 / 2

3.5

>>>

Python also provides a plural, and the method is to use J and J as an imaginary unit, such as 1 1j, 3.14e-10j, and so on.

3.2. String Python can handle strings in addition to the digital, the string is built by single-chanpoh or double apostrophe:

>>> '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. '

>>>

The string output format is the same as the input look, all with an apostrophe package, apostrophe, and other special characters with a backslash transfusion. If there is a single coviation in the string without double apostrophe, use a double apostrophe package, otherwise you should be wrapped in a single pennock. The Print statement to be described later may not have an apostrophe or escape output string. The string can be connected with number, repeat with *.

>>> Word = 'Help' 'A'

>>> Word

'Helpa'

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

''

>>>

The string can be used with the subscript index like it in C, the first character of the string is 0.

Python has no separate character data types, and a character is a string of length one. As in the ICON language, you can specify a substring with a slice mark, and the clip is separated by a colon.

>>> Word [4]

'A'

>>> Word [0: 2]

'HE'

>>> Word [2: 4]

'lp'

>>>

The fragment has a good default: the first subscript omitrates the default to zero, the second subscript is omitted to the length of the string.

>>> Word [: 2] # Two characters

'HE'

>>> Word [2:] # In addition to the first two strings

'lpa'

>>>

Note that S [: i] S [i:] is equal to S is a useful range of constant equations of fragment operations.

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

'Helpa'

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

'Helpa'

>>>

The unreasonable clip can be well received: excessive subscript is swapped into a string length, and the upper bound is smaller than the lower boundary.

>>> Word [1: 100]

'ELPA'

>>> Word [10:]

'' '

>>> Word [2: 1]

'' '

>>>

The subscript is allowed to be negative, then the left left left. E.g:

>>> Word [-1] # last character

'A'

>>> Word [-2] # Countdown second character

'P'

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

'PA'

>>> Word [: - 2] # In addition to the part of the last two characters

'HEL'

>>>

But should you pay attention to the actual or 0, so it won't be left from right!

>>> Word [-0] # (because -0 is equal to 0)

'H'

>>>

Over the range of fragments are truncated, but don't do this in a non-fragment:

>>> Word [-100:]

'Helpa'

>>> Word [-10] # 错误

TRACEBACK (InnerMost Last):

File "", Line 1

IndexError: String Index Out of Range >>>

The best way to remember fragment is to see the subscript as a point between characters, the left boundary number of the first character is 0. The right boundary of the last character of the N-character string is N, for example:

- - - - -

| H | E | L | P | A |

- - - - -

0 1 2 3 4 5

-5 -4 -3 -2 -1

The first row of numbers give a position of the subscript 0 to 5 in the string, and the second line gives the corresponding negative date. The fragment from I to J consists of characters between boundaries I and j.

For non-negative subscripts, if the subscript is in the boundary, the length of the clip is the difference in the subscript. For example, the length of Word [1: 3] is 2.

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

>>> s = 'supercalifragilisticexpialidocious'

>>> LEN (S)

34

>>>

Multi-line long strings can also be continued in a row of backslash, and the heads of the row do not be ignored, such as

Hello = "this is a rather long string containing / n several line of text just as you.

Print Hello

Resulting

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.

For a particularly long string (such as a few paragraphs containing the description), if each line is used in the above way, it is very troublesome, especially the powerful editor such as Emacs. . In this case, tropolism can be used, for example

Hello = "" "

This String is bounded by Triple Double Quotes (3 Times ").

Unescaped newlines in The String Are Retained, Though It Is Still Possible / NTO USE All Normal Escape Sequences.

Whitespace at the beginning beginning of a line is

Significant. if you need to include Three Opening quotes

You have to escape at least one of them, e.g. / "" "".

THIS STRING Ends in a newline.

"" "

Triple apostrophe strings can also be used with three single codons, without any semantic differences.

Multi-line string constants can be directly connected, with space separation between string constants, which can be automatically connected when compiling, this can connect a long string without sacrificing indent alignment or performance, not like The plus connection needs to operate, nor does it take to keep the first space in the string need to be maintained.

3.3 list

There are several composite data types in Python to combine other values ​​together. The most flexible is a list, which can be written in a number of values ​​(items) separated by commas between square brackets. The items of the list do not have to take the same type. >>> a = ['spam', 'Eggs', 100, 1234]

>>> a

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

>>>

Like the string, the list subscript starts from 0, the list can be taken, can be connected, 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 a string is that the list is variable, you can modify each element of the list:

>>> A

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

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

>>> A

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

>>>

You can also re-value a fragment, which can even change the size of the table:

>>> # Replace the number of items:

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

>>> A

[1, 12, 123, 1234]

>>> # Remove several items:

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

>>> A

[123, 1234]

>>> # Insert a number of items:

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

>>> a

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

>>> a [: 0] = a # Insert itself at the beginning

>>> a

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

>>>

Built-in functions are also used in list:

>>> LEN (a)

8

>>>

You can build a nested list (the elements of the table is also a list), such as:

>>> q = [2, 3]

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

>>> LEN (P)

3

>>> p [1]

[twenty three]

>>> P [1] [0]

2

>>> P [1] .Append ('XTRA') #List Method >>> P

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

>>> Q

[2, 3, 'XTRA']

>>>

Note that P [1] and Q actually in this example are the same object! That is to say, they are just two names of the same thing (reference).

3.4 Programming Preliminary

Python is of course not only used to add two numbers to complete it. For example, we can write a few startings of the Fibonacci sequence:

>>> # Fibonacci Sequence:

... # Two elements and definitions Next

... a, b = 0, 1

>>> While B <10:

... Print B

... a, b = b, A B

...

1

1

2

3

5

8

>>>

This example introduces several new features.

The first line contains a multiple assignment: variables A and B simultaneously get new values ​​0 and 1. In the last row, I used multiple assignments, and we can see that the right side is calculated and then assigned.

The While cycle is constantly being performed when the cycle condition (here: B <10) is established. As in Python in Python, the non-zero integer value is true, zero is a false value. The condition can also be a string or list or any sequence, the length is non-zero, and the null sequence is false. The example used in the example is a simple comparison. Standard comparison operators are the same as C:

<,>, ==, <=,> = and! =.

The cyclic body is indent: indentation is the way Python used to combine the statement. Python is currently not available to intelligent automatic indentation, so you need to type yourself for each shrinkage or space. In actual use you can use the text editor to prepare complex inputs for Python, and most text editing programs have automatic indentation. A blank line is required to indicate the completion of the complex statement when entering the complex statement when interacting into the complex statement. The PRINT statement displays the rear expressive value. This is different from the direct written expression, which can display multiple expressions and strings and can be used in program files. When the string is displayed, there is no apostrophe. Insert a space between each item, so you can display in a beautiful format, such as:

>>> i = 256 * 256

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

The Value of I is 65536

>>>

Write a comma at the end to avoid the last wrap:

>>> 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

>>>

Note If the system does not end, the system will go first before the prompt is displayed.

Python also provides an output mode of the same Printf format as a C language, which is implemented by%, and the left is format, such as:

>>> Print 'The value of 1/7 is approximately% 5.3f.'% 0.142857

The value of 1/7 is ApproxImately 0.143.

>>>

If there is a number of items that need to be output, the items on the right side of the item can be a sequence group, such as >>> Print "Name:% -10S Age:% 3D"% ("White", 31)

Name: White agn: 31

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

New Post(0)