Chapter 3 Basic use
Below we use examples to introduce the basic usage of Python. In the example, user input and system output are differentiated by whether there are any prompts (>>> and...). If you want to try these examples, you need to type all the commands after the prompt. The lines that are not prompted in the example are the output of the system. Note that only the second prompted line means that a blank line needs to be typed, which is used to end the multi-line command.
3.1 Use Python as a calculator
Start the interpreter and wait for the main prompt >>> to appear. The interpreter can be used as a calculator. Type an expression and the interpreter can output the result. The way of writing expressions is very intuitive: the functions of operators such as +, -, *, /, %, ** are no different from those of most other languages (such as Pascal or C). Parentheses can be used to combine. For example:
>>> 2+2
4
>>> # This is a comment
... 2+2
4
>>> 2+2 # Comments on the same line as the code
4
>>> (50-5*6)/4
5
>>> # Integer division gets the following integer
... 7/3
2
>>> 7/-3
-3
>>>
Like in C, the equal sign is used to assign a value to a variable, and the result of the assignment is not displayed:
>>> width = 20
>>> height = 5*9
>>> width * height
900
>>>
You can assign the same value to several variables at the same time:
>>> x = y = z = 0 # Give x, y and z
>>> x
0
>>> y
0
>>> z
0
>>>
Python fully supports floating point numbers. Mixed types of operations will convert integers into floating point numbers first:
>>> 4 * 2.5 / 3.3
3.0303030303
>>> 7.0 / 2
3.5
>>>
Python also provides complex numbers by using j and J as imaginary units, such as 1+1j, 3.14e-10j, etc.
3.2. String
In addition to processing numbers, Python can also process strings, which are wrapped with single or double apostrophes:
>>> '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 output format of the string is the same as the input, and they are wrapped with apostrophes and other special characters are escaped with backslashes. If there is a single apostrophe in the string and no double apostrophe, it is wrapped with a double apostrophe, otherwise it should be wrapped with a single apostrophe. The print statement to be introduced later can output strings without apostrophes or escapes.
The string can be connected with the + sign, and repeated with the * sign:
>>> word = 'Help' + 'A'
>>> word
'HelpA'
>>> '<' + word*5 + '>'
'<HelpAHelpAHelpAHelpAHelpA>'
>>>
A string can be indexed with a subscript like in C, and the first character of the string is subscripted to 0.
Python does not have a separate character data type, a character is a string of length one. As in the Icon language, substrings can be specified with slice notation, and fragments are two subscripts separated by colons.
>>> word[4]
'A'
>>> word[0:2]
'He'
>>> word[2:4]
'lp'
>>>
The fragment has a good default value: the default is zero when omitted in the first subscript, and the default is the length of the string when omitted in the second subscript.
>>> word[:2] # First two characters
'He'
>>> word[2:] # Parts except the first two strings
'lpA'
>>>
Note that s[:i] + s[i:] equals s is a useful identity for fragment operations.
>>> word[:2] + word[2:]
'HelpA'
>>> word[:3] + word[3:]
'HelpA'
>>>
Unreasonable fragment subscripts can be explained well: an oversized subscript is replaced with a string length, and an empty string is returned when the upper bound is smaller than the lower bound.
>>> word[1:100]
'elpA'
>>> word[10:]
''
>>> word[2:1]
''
>>>
The subscript is allowed to be a negative number, and then the number is from right to left. For example:
>>> word[-1] #The last character
'A'
>>> word[-2] # The second-last character
'p'
>>> word[-2:] # The last two characters
'pA'
>>> word[:-2] # Parts except the last two characters
'Hel'
>>>
But it should be noted that -0 is actually still 0, so it will not count from right to left!
>>> word[-0] #(Because -0 is equal to 0)
'H'
>>>
The subscript of the fragment outside the range is truncated, but do not do this in non-fragmented cases:
>>> word[-100:]
'HelpA'
>>> word[-10] #Error
Traceback (innermost last):
File "<stdin>", line 1
IndexError: string index out of range
>>>
The best way to remember the meaning of a fragment is to regard the subscript as a dot between characters, with the left boundary number of the first character being 0. The right boundary of the last character of a string with n characters is n, for example:
+---+---+---+---+---+
| H | e | l | p | A |
+---+---+---+---+---+
0 1 2 3 4 5
-5 -4 -3 -2 -1
The first line of numbers gives the positions of subscripts 0 to 5 in the string, and the second line of numbers gives the corresponding negative subscript. The fragment from i to j consists of characters between the boundaries i and j.
For non-negative subscripts, if the subscripts are all within the bounds, the length of the segment is the difference of the subscript. For example, word[1:3] is 2 in length.
The built-in function len() returns the length of the string:
>>> s = 'supercalifragilisticexpialidocious'
>>> len(s)
34
>>>
Long strings with multiple lines can also be continued with a backslash at the end of the line. The blank space at the beginning of the line is not ignored, such as
hello = "This is a rather long string containing\n\
several lines of text just as you would do in C.\n\
Note that whitespace at the beginning of the line is\
significant.\n"
print hello
The result is
This is a rather long string containing
several lines of text just as you would do in C.
Note that whitespace at the beginning of the line is significant.
For particularly long strings (such as several paragraphs containing descriptions), it is very troublesome to end each line with \n\ in the above method, especially so it cannot be reorganized with a powerful editor like Emacs. For this case, a triple apostrophe can be used, e.g.
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 of a line is
significant. If you need to include three opening quotes
you have to escape at least one of them, . \""".
This string ends in a newline.
"""
A triple apostrophe string can also be used with three single apostrophes without any semantic differences.
Multi-line string constants can be directly connected, and string constants can be separated by spaces, which can be automatically connected at compile time. This way, a long string can be connected without sacrificing indent alignment or performance. It is not like connecting with plus signs that requires calculation, nor is it like newlines in string strings whose first space needs to be maintained.
3.3 List
There are several composite data types in Python that are used to combine other values together. The most flexible one is the list, which can be written as several values (items) separated by commas between square brackets. Items in the list do not have to be of the same type.
>>> a = ['spam', 'eggs', 100, 1234]
>>> a
['spam', 'eggs', 100, 1234]
>>>
Like string subscripts, list subscripts start from 0, lists can take fragments, connect, etc.:
>>> 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 strings, lists are mutable and each element of the list can be modified:
>>> a
['spam', 'eggs', 100, 1234]
>>> a[2] = a[2] + 23
>>> a
['spam', 'eggs', 123, 1234]
>>>
You can also reassign a fragment, which can even change the table size:
>>> # Replace several items:
... a[0:2] = [1, 12]
>>> a
[1, 12, 123, 1234]
>>> # Remove several items:
... a[0:2] = []
>>> a
[123, 1234]
>>> # Insert several items:
... a[1:1] = ['bletch', 'xyzzy']
>>> a
[123, 'bletch', 'xyzzy', 1234]
>>> a[:0] = a # Insert yourself at the beginning
>>> a
[123, 'bletch', 'xyzzy', 1234, 123, 'bletch', 'xyzzy', 1234]
>>>
Built-in functions are also used in lists:
>>> len(a)
8
>>>
A nested list can be created (the elements of the table are also lists), such as:
>>> q = [2, 3]
>>> p = [1, q, 4]
>>> len(p)
3
>>> p[1]
[2, 3]
>>> p[1][0]
2
>>> p[1].append('xtra') �
>>> p
[1, [2, 3, 'xtra'], 4]
>>> q
[2, 3, 'xtra']
>>>
Note that in this example, p[1] and q are actually the same object! In other words, they are just two names (quotes) of the same thing.
3.4 Preliminary programming
Of course, Python is not only used to add two numbers together, it can do very complicated tasks. For example, we can write out the beginnings of the Fibonacci sequence:
>>> # Fibonacci Sequence:
... # 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: variables a and b obtain the new values 0 and 1 at the same time. Multiple assignments are used in the last line. We can see that when assigning, we first calculate the right side and then assign the value.
While loops are constantly executed when the loop condition (here: b < 10) is established. In Python, like in C, non-zero integer values are true values and zero values are false values. The condition can also be a string or a list or any sequence, with a non-zero length being true and a false sequence being empty. The example is a simple comparison. The standard comparison operator is the same as C:
<, >, ==, <=, >= and !=.
The loop body is indented: indentation is the way Python uses to combine statements. Python does not currently provide intelligent automatic indentation, so you need to type tabs or spaces for each indentation yourself. In actual use, you can use text editing programs to prepare complex input for Python. Most text editing programs have the function of automatic indentation. When entering a compound statement interactively, an empty line is required to indicate the completion of the compound statement (because the interpreter cannot guess which is the last line of the statement). The print statement displays the following expression value. This is different from writing expressions directly, it can display multiple expressions and strings, and can be used in program files. When displaying, the string has no apostrophes, and a space is inserted between the items, so you can display it in a beautiful format, such as:
>>> i = 256*256
>>> print 'The value of i is', i
The value of i is 65536
>>>
Writing a comma at the end can avoid the last line break:
>>> 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 if the previous line does not end, the system will wrap the line before displaying the prompt.
Python also provides the same printf format output method as C language, which is implemented using % and the format on the left is, 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 are multiple items that need to be output, the items on the right side of the percentage sign can be a sequence, such as
>>> print "Name: %-10s Age: %3d" % ("White", 31)
Name: White Age: 31
Previous page12345678910Next pageRead the full text