The Python Tutorial 3——An Informal Introduction to Python

1、Comment

Comments in Python start with the hash character,#, and extend to the end of the physical line. A comment mayappear at the start of a line or following whitespace or code, butnot within a string literal. A hash character within a string literal is just a hash character.Since comments are to clarify code and are not interpreted by Python, they maybe omitted when typing in examples.

Some examples

# this is the first comment
spam = 1  # and this is the second comment
          # ... and now a third!
text = "# This is not a comment because it's inside quotes."

2、Number

>>> 17 / 3  # int / int -> int
5
>>> 17 / 3.0  # int / float -> float
5.666666666666667
>>> 17 // 3.0  # explicit floor division discards the fractional part
5.0
>>> 17 % 3  # the % operator returns the remainder of the division
>>> 5 ** 2  # 5 squared
25
>>> 2 ** 7  # 2 to the power of 7
128

3、String

1)If you don’t want characters prefaced by \ to be interpreted as special characters, you can useraw strings by adding an r before  the first quote:  r保持字符串原貌

>>> print 'C:\some\name'  # here \n means newline!
C:\some
name
>>> print r'C:\some\name'  # note the r before the quote
C:\some\name

2) String literals can span multiple lines. One way is using triple-quotes:"""...""" or'''...'''. End of lines are automatically included in the string, but it’s possible to prevent this by adding a \at the end of the line. The following example:

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

produces the following output (note that the initial newline is not included):

Usage: thingy [OPTIONS]
     -h                        Display this usage message
     -H hostname               Hostname to connect to
对比

print """
Usage: thingy [OPTIONS]
     -h                        Display this usage message
     -H hostname               Hostname to connect to
"""
produces the following output

 
Usage: thingy [OPTIONS]
     -h                        Display this usage message
     -H hostname               Hostname to connect to
 
3)Strings can be concatenated (glued together) with the + operator, and repeated with *:

>>> # 3 times 'un', followed by 'ium'
>>> 3 * 'un' + 'ium'
'unununium'

Two or more string literals (i.e. the ones enclosed between quotes) next to each other are automatically concatenated.

>>> 'Py' 'thon'
'Python'

This only works with two literals though, not with variables or expressions:

>>> prefix = 'Py'
>>> prefix 'thon'  # can't concatenate a variable and a string literal
  ...
SyntaxError: invalid syntax
>>> ('un' * 3) 'ium'
  ...
SyntaxError: invalid syntax

If you want to concatenate variables or a variable and a literal, use +:

>>> prefix + 'thon'
'Python'

Strings can be indexed (subscripted), with the first character having index 0.There is no separate character type; a character is simply a string of size one:

>>> word = 'Python'
>>> word[0]  # character in position 0
'P'
>>> word[5]  # character in position 5
'n'

Indices may also be negative numbers, to start counting from the right:

>>> word[-1]  # last character
'n'
>>> word[-2]  # second-last character
'o'
>>> word[-6]
'P'

Note that since -0 is the same as 0, negative indices start from -1.

4)In addition to indexing, slicing is also supported. While indexing is used to obtain individual characters, slicing allows you to obtain a substring:

>>> word[0:2]  # characters from position 0 (included) to 2 (excluded)
'Py'
>>> word[2:5]  # characters from position 2 (included) to 5 (excluded)
'tho'

5)Python strings cannot be changed — they areimmutable.Therefore, assigning to an indexed position in the string results in an error:

>>> word[0] = 'J'
  ...
TypeError: 'str' object does not support item assignment
6)The built-in function len() returns the length of a string:
>>> s = 'supercalifragilisticexpialidocious'
>>> len(s)
34

4、List

1)Python knows a number of compound data types, used to group together other values. The most versatile is thelist, which can be written as a list of comma-separated values (items) betweensquare brackets. Lists might contain items ofdifferent types, but usually the items all have the same type.

>>> squares = [1, 4, 9, 16, 25]
>>> squares
[1, 4, 9, 16, 25]

>>> ls=[2,'s',3]
>>> ls
[2, 's', 3]

2)Lists also supports operations like concatenation:

>>> squares + [36, 49, 64, 81, 100]
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
3)You can also add new items at the end of the list, by using the append() method (we will see more about methods later):
>>> cubes = [1, 8, 27, 64, 125]
>>> cubes.append(216)  # add the cube of 6
>>> cubes.append(7 ** 3)  # and the cube of 7
>>> cubes
[1, 8, 27, 64, 125, 216, 343]
4)

The built-in function len() also applies to lists:

>>> letters = ['a', 'b', 'c', 'd']
>>> len(letters)
4

5、first step programming

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

This example introduces several new features.

  • The first line contains a multiple assignment: the variables a and bsimultaneously get the new values 0 and 1. On the last line this is used again,demonstrating that the expressions on the right-hand side are all evaluated first before any of the assignments take place. The right-hand side expressions are evaluated from the left to the right.

  • The while loop executes as long as the condition (here:b<10)remains true. In Python, like in C, any non-zero integer value is true; zero is false.The condition may also be a string or list value, in fact any sequence;anything with a non-zero length is true, empty sequences are false. The test used in the example is a simple comparison. The standard comparison operators are written the same as in C:< (less than),> (greater than),==(equal to),<= (less than or equal to),>= (greater than or equal to)and!= (not equal to).

  • The body of the loop is indented:indentation is Python’s way of grouping statements. At the interactive prompt, you have to type atab or space(s) for each indented line. In practice you will prepare more complicated input for Python with a text editor; all decent text editors have an auto-indent facility. When a compound statement is entered interactively, it must be followed by a blank line to indicate completion(since the parser cannot guess when you have typed the last line). Note that each line within a basic block must be indented by the same amount.

  • The print statement writes the value of the expression(s) it is given. It differs from just writing the expression you want to write (as we did earlier in the calculator examples) in the way it handles multiple expressionsand strings. Strings are printed without quotes, and a space is inserted between items, so you can format things nicely, like this:

>>> i = 256*256
>>> print 'The value of i is', i
The value of i is 65536

A trailing comma avoids the newline after 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

Note that the interpreter inserts a newline before it prints the next prompt if the last line was not completed

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值