Python Manual Notes1

來源:互聯網
上載者:User

python3.1似乎和以前的2.X版本不同了。至少 print ‘hello world’被認為是語法錯誤,而要寫成函數形式—— print(“hello world”)

1. Comments in Python start with the hash character, #, and extend to the end of the physical line. A hash character within a string literal is just a hash character.

STRING = "# This is not a comment."

 

2. numbers

1)

>>> 8/5 # Fractions aren't lost when dividing integers1.6

2)To do integer division and get an integer result, discarding any fractional result, there is another operator, //:

>>> # Integer division returns the floor:... 7//32>>> 7//-3-3

3)Variables must be “defined” (assigned a value) before they can be used, or an error will occur.

4)Complex numbers are also supported; imaginary numbers are written with a suffix of j or J. Complex numbers with a nonzero real component are written as (real+imagj), or can be created with the complex(real, imag) function.

To extract these parts from a complex number z, use z.real and z.imag.

The conversion functions to floating point and integer (float(), int()) don’t work for complex numbers — there is not one correct way to convert a complex number to a real number. Use abs(z) to get its magnitude (as a float) or z.real to get its real part:

 

3.Strings

1) They can be enclosed in single quotes or double quotes. Pay attention to the \ in the string.

>>> 'doesn\'t'"doesn't">>> "doesn't""doesn't">>> '"Yes," he said.''"Yes," he said.'>>> "\"Yes,\" he said."'"Yes," he said.'

2)Continuation lines can be used, with a backslash as the last character on the line indicating that the next line is a logical continuation of the line.

Note that whitespace at the beginning of the line is\ significant."

3)strings can be surrounded in a pair of matching triple-quotes: """ or '''. End of lines do not need to be escaped when using triple-quotes, but they will be included in the string.

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

4)If we make the string literal a “raw” string, \n sequences are not converted to newlines, but the backslash at the end of the line, and the newline character in the source, are both included in the string as data.

code:

hello = r"This is a rather long string containing\n\several lines of text much as you would do in C."print(hello)

result:

This is a rather long string containing\n\several lines of text much as you would do in C.

5)Strings can be concatenated (glued together) with the + operator, and repeated with *:

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

6)Two string literals next to each other are automatically concatenated; the first line above could also have been written word = 'Help' 'A'; this only works with two literals, not with arbitrary string expressions:

>>> 'str'.strip() + 'ing'   #  <-  This is ok'string'>>> 'str'.strip() 'ing'     #  <-  This is invalid

7)Slice indices have useful defaults; an omitted first index defaults to zero, an omitted second index defaults to the size of the string being sliced.

>>> word'HelpA'>>> word[2:4]'lp'>>> word[2:]    # Everything except the first two characters'lpA'

8)Unlike a C string, Python strings cannot be changed. Assigning to an indexed position in the string results in an error.However, creating a new string with the combined content is easy and efficient. Degenerate slice indices are handled gracefully: an index that is too large is replaced by the string size, an upper bound smaller than the lower bound returns an empty string.

>>> word[0] = 'x'   #invalid>>> word[:2] + word[2:]'HelpA'>>> word[10:]''>>> word[2:1]''

9)Indices may be negative numbers, to start counting from the right. But note that -0 is really the same as 0, so it does not count from the right! Out-of-range negative slice indices are truncated, but don’t try this for single-element (non-slice) indices. For example:

>>> word[-2]     # The last-but-one character'p'>>> word[:-2]    # Everything except the last two characters'Hel'>>> word[-0]     # (since -0 equals 0)'H'>>> word[-100:]'HelpA'>>> word[-10]    # error

10)The built-in function len() returns the length of a string.

4. Unicode

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

5. Lists

The most versatile is the list, which can be written as a list of comma-separated values (items) between square brackets. List items need not all have the same type.

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

Unlike strings, which are immutable, it is possible to change individual elements of a list.

It is possible to nest lists (create lists containing other lists), for example:

 

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

 

6. Programming

The body of the loop is indented: indentation is Python’s way of grouping statements. Python does not (yet!) provide an intelligent input line editing facility, so you have to type a tab or space(s) for each indented line.

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

>>> a, b = 0, 1>>> while b < 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
相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.