In the following example, the input and output are prompted by a greater-than sign and a period (>>> and…), respectively. Note: If you want to reproduce these examples, type lines of code that do not contain the prompt after the interpreter prompt. Note that the dependent prompt encountered in the exercise means that you need to type an extra blank line at the end before the interpreter knows that this is the end of a multi-line command.

Many of the examples in this manual — including those with interactive prompts — contain comments. Comments in Python start with the # character and continue to the end of the actual line. Comments can start at the beginning of a line, after whitespace or code, but do not appear in the string. The # character in a text string simply represents #. Comments in the code are not interpreted by Python and can be ignored when typing examples.

Here is an example:

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.” 3.1. Using Python as a calculator Let’s try some simple Python commands. Start the interpreter and wait for the main prompt >>> to appear (which doesn’t take long).

3.1.1. The digital interpreter behaves like a simple calculator: you type expressions into it and it returns a value. The expression syntax is straightforward: the operators +, -, * and/are the same as in any other language (e.g., Pascal or C); Parentheses (()) are used to group. Such as:

2 + 2


4


50 – 5*6


20


50 minus 5 times 6 over 4


5.0


8 / 5 # division always returns a floating point number


1.6


Integers (for example, 2, 4, 20) are of type int, and numbers with fractional parts (for example, 5.0, 1.6) are of type float. We’ll see more about numeric types later in this tutorial.

Division (/) always returns a floating point number. To use floor division and get an integer result (dropping any decimal parts), you can use the // operator; To calculate the remainder you can use %

17/3 # Classic Division returns a float 5.6666666666667

17 // 3 # floor division discards the fractional part 5 17 % 3 # the % operator returns the remainder of the division 2 5 3 + 2 # Result divisor + remainder 17 With Python, power powers can also be computed using the ** operator [1]:

5 ** 2 # 5 squared 25 2 ** 7 # 2 to the power of 7 After an assignment, no result is displayed until the next prompt:

Width = 20 height = 5*9 width * height 900

try to access an undefined variable

. N Traceback (most recent call last): File ”

“, line 1, in

NameError: Name ‘n’ is not defined floating point is fully supported; In a mixed calculation of integers and floating-point numbers, the integers are converted to floating-point numbers:

3 * 3.75/1.5 7.5 7.0/2 3.5 In interactive mode, the last expression value is assigned to the variable _. This way we can use it as a desktop calculator, handy for continuous calculations, such as:

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 assign a value to it — you’ll just create a separate local variable with the same name, which shields the magic of system built-in variables.

In addition to int and float, Python supports other numeric types such as Decimal and Fraction. Python also has built-in support for complex numbers, using the suffix J or J for imaginary parts (for example, 3+5j).

Python also provides strings that can be represented in several different ways than numbers. They can be used in single quotes (‘… ‘) or double quotes (“…”) ) identification [2]. \ can be used to escape quotes:

‘spam eggs’ # single quotes ‘spam eggs’ ‘doesn\’t’ # use \’ to escape the single quote… “doesn’t” “doesn’t” # … or use double quotes instead “doesn’t” ‘”Yes,” he said.’ ‘”Yes,” he said.’ “\”Yes,\” he said.” ‘”Yes,” he said.’ ‘”Isn\’t,” she said. “‘”Isn\’t,” she said.’ In an interactive interpreter, the output string is enclosed in quotes, and special characters are escaped by backslashes. The two strings are equal, although they may not look the same as the input. If the string has only single quotes but no double quotes, use double quotes, otherwise use single quotes. The print() function produces more readable output by leaving out quotes and printing out escaped special characters:

‘”Isn\’t,” she said.’ ‘”Isn\’t,” she said.’ print(‘”Isn\’t,” she said.’) “Isn’t,” she said. s = ‘First line.\nSecond line.’ # \n means newline s # without print(), \n is included in the output ‘First line.\nSecond line.’ print(s) # with print(), \n produces a new line First line. Second line. If you are treating a character preceded by a \ as a special character, you can use the original string by placing an R before the first quote:

print(‘C:\some\name’) # here \n means newline! C:\some ame print(r ‘c :\some\name’) # note the r before the quote C:\some\name String text can be divided into multiple lines. One way is to use triple quotes: “””…” “” or” ‘… “‘. End-of-line newlines are automatically included in the string, but you can avoid this behavior by adding \ to the end of the line. Here’s an example: You can use a continuous string at the end of a line with a backslash, which indicates that the next line is logically following that line:

print(“””\

Usage: thingy [OPTIONS]

 -h                        Display this usage message
 -H hostname               Hostname to connect to

“””) will generate the following output (note that there is no starting line) :

Usage: thingy [OPTIONS]

 -h                        Display this usage message
 -H hostname               Hostname to connect to

Strings can be concatenated (pasted together) by the + operator, and can be repeated by * :

3 times ‘un’, followed by ‘ium’

3 * ‘UN’ + ‘ium’ ‘unununium’ Two contiguous string texts are automatically concatenated together. :

‘Py’ ‘thon’ ‘Python’ it is only used for two string texts and cannot be used for string 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 multiple variables or concatenate a variable with a string text, use +:

Prefix + ‘thon’ ‘Python’ is especially useful if you want to split long strings:

text = (‘Put several strings within parentheses ‘

        'to have them joined together.')

Text ‘Put several strings within parentheses to have them joined together.’ Like C, the first character of the string has an index of 0. Python does not have a single character type; A character is simply a string of length 1. :

Word = ‘Python’ word[0] # character in position 0 ‘P’ word[5] # character in position 5 ‘n’ Such as:

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

Note that negative 0 is actually 0, so it doesn’t cause the calculation to start on the right.

In addition to indexes, slicing is also supported. Indexes are used to get a single character, and slicing lets you get 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'

Note that the beginning character is included, but the end character is not. This makes s[: I] + s[I :] always equal to S:

>>> word[:2] + word[2:]
'Python'
>>> word[:4] + word[4:]
'Python'

Slice indexes have useful defaults; The first omitted index defaults to zero, and the second omitted index defaults to the size of the sliced string. :

>>> word[:2]  # character from the beginning to position 2 (excluded)
'Py'
>>> word[4:]  # characters from position 4 (included) to the end
'on'
>>> word[-2:] # characters from the second-last (included) to the end
'on'

Here’s an easy way to remember how slicing works: the index for slicing is between two characters. The index of the first character on the left is 0, and the index of the right bound of the last character on a string of length n is n. Such as:

 +---+---+---+---+---+---+
 | P | y | t | h | o | n |
 +---+---+---+---+---+---+
 0   1   2   3   4   5   6
-6  -5  -4  -3  -2  -1

The first line of numbers in the text gives the index point 0 in the string… 6. The second row gives the corresponding negative index. The slice is all the characters between the numerically marked boundaries I through J.

For non-negative indexes, if both the top and bottom are within the boundary, the slice length is the difference between the two indexes. For example, Word [1:3] is 2.

Trying to use an index that is too large will result in an error:

>>> word[42]  # the word only has 6 characters
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: string index out of range

Python handles slice indexes that don’t make sense: an index that is too large (that is, the subscript value is greater than the actual string length) is replaced by the actual string length, and an empty string is returned when the top boundary is larger than the bottom boundary (that is, the slice lvalue is greater than the Rvalue) :

>>> word[4:42]
'on'
>>> word[42:]
''

Python strings cannot be changed – they are immutable. Therefore, assigning the position to the string index results in an error:

>>> word[0] = 'J'
  ...
TypeError: 'str' object does not support item assignment
>>> word[2:] = 'py'
  ...
TypeError: 'str' object does not support item assignment

If you need a different string, you should create a new one:

>>> 'J' + word[1:]
'Jython'
>>> word[:2] + 'py'
'Pypy'

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

>>> s = 'supercalifragilisticexpialidocious'
>>> len(s)
34

See also

  • [Text Sequence Type — STR]

    Strings are examples of sequence types that support this type of common operation.

  • [String Methods]

    Both strings and Unicode strings support a number of methods for basic conversions and lookups.

  • [String Formatting]

    This describes the information for string formatting using [str.format()].

  • [String Formatting Operations]

    This describes the old-style string formatting operations that are called when the string and Unicode string are the left-hand operand of the % operator. If you do meet a good colleague, you’ll be lucky. Go ahead and learn. Python, PythonWeb, crawler, data analysis and other Python skills, as well as learning methods of artificial intelligence, big data, data mining, office automation and so on. Build from zero foundation to project development start combat all-round analysis!

3.1.3. List

Python has several complex data types that are used to represent other values. The most common is list, which can be written as a comma-separated list of values between brackets. The elements of a list need not be of the same type:

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

Just like strings (and all other built-in [sequence] types), lists can be indexed and sliced:

>>> squares[0]  # indexing returns the item
1
>>> squares[-1]
25
>>> squares[-3:]  # slicing returns a new list
[9, 16, 25]

All slicing operations return a new list of requested elements. This means that the following slice operation returns a new (shallow) copy of the list:

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

Lists also support operations like join:

>>> squares + [36, 49, 64, 81, 100]
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

Unlike an immutable string, a list is mutable and allows you to modify the elements:

>>> cubes = [1, 8, 27, 65, 125]  # something's wrong here
>>> 4 ** 3  # the cube of 4 is 64, not 65!
64
>>> cubes[3] = 64  # replace the wrong value
>>> cubes
[1, 8, 27, 64, 125]

You can also add new elements to the end of the list using the append() method (we’ll see more about list methods later) :

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

You can also assign a value to the slice, which changes the size of the list, or empties it:

>>> letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g']
>>> letters
['a', 'b', 'c', 'd', 'e', 'f', 'g']
>>> # replace some values
>>> letters[2:5] = ['C', 'D', 'E']
>>> letters
['a', 'b', 'C', 'D', 'E', 'f', 'g']
>>> # now remove them
>>> letters[2:5] = []
>>> letters
['a', 'b', 'f', 'g']
>>> # clear the list by replacing all the elements with an empty list
>>> letters[:] = []
>>> letters
[]

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

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

Allows nested lists (creating a list that contains other lists), for example:

>>> a = ['a', 'b', 'c']
>>> n = [1, 2, 3]
>>> x = [a, n]
>>> x
[['a', 'b', 'c'], [1, 2, 3]]
>>> x[0]
['a', 'b', 'c']
>>> x[0][1]
'b'

3.2. The first step of programming

Of course, we can do more complicated things with Python than just adding two and two. For example, we can write a program that generates a Fibonacci subsequence like this:

>>> # Fibonacci series: ... # the sum of two elements defines the next ... a, b = 0, 1 >>> while b < 10: ... print(b) ... a, b = b, a+b ... One, one, two, three, five, eight

This example introduces several new features.

  • The first line contains a multiple assignment: variables a and b get new values 0 and 1 at the same time, and the last line is used again.

    In this demonstration, the right-hand side is evaluated first before the variable is assigned. The right-hand expression evaluates from left to right.

  • The [while] loop executes when the condition (in this case b < 10) is true. In Python, like IN C, any non-zero integer is true; 0 is false. A condition can also be a string or a list, or in fact any sequence;

    All non-zero length sequences are true, empty sequences are false. The test in the example is a simple comparison. The standard comparison operators are the same as C: <, >, ==, <=, >= and! =.

  • The body of the loop is indented: indentation is Python’s way of organizing statements. Python doesn’t (yet) provide integrated line editing, so you have to type a TAB or space for each indentation.

    In practice, it is recommended that you find a text editor to type complex Python programs. Most text editors provide automatic indentation. When interactively typing compound statements, you must end with a blank line (because the interpreter can’t guess which line you typed is the last). Note that each line in the same block must be indented by the same amount of white space. To help you on your way to learning Python, you can take a course from a Python expert. He has free live classes on the Internet at 8 PM every night. He will talk about Python in a very easy to understand and funny way. The greatest value of learning Python from a master is to listen to your words for ten years. The value of self-study is that it is better to study by yourself for half a year than to have a master teach you a day, 365 days a year. He will teach you every night, and there are students who like to listen to it. To his WeiXin * (in Chinese) : in the front row is: 762, in the middle of a row is: 459, the back of a set of is: 510, the above three group of letters can be combined in accordance with the order, very simple, Newton once said, standing on the shoulders of others, you will see higher and further, all rivers run into sea, to conquer the python world of the ocean.

  • The keyword [print()] statement outputs the value of the given expression. It controls multiple expressions and string output to the string you want (just like we did in the previous calculator example).

    Instead of enclosing the string in quotes, insert space between every two subitems, so you can format it nicely, like this:

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

    To disallow newlines, end with a comma:

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

Footnotes

[[1]] (http://www.pythondoc.com/pyth… because六四事件Has a higher priority than-, so- 3 * * 2Will be interpreted as- (3 * * 2)And the results for9 -. In order to avoid that and get9, you can use(3) * * 2.
[[2]] (http://www.pythondoc.com/pyth… Unlike other languages, special characters such as\nIn single quotation marks ('... ') and double quotation marks ("...") has the same meaning. The only difference is that in single quotes, you don’t have to escape"(But you have to escape') and vice versa.

[Next] “4. Using the Python interpreter “)

\