The first step in programming python, the python as a calculator to

Introduction to Python

In the following example, the input and output respectively and periods of greater-than prompt (  >>> and  ... label): To repeat the example, after the interpreter will prompt input (hereinafter prompt) that do not contain prompt line of code. Note that encountered in practice subordinate prompt indicates that you need a blank line at the end of a multi-input, the interpreter to know that this is the end of a multi-line command.

This manual contains many examples - including those with interactive prompt - contains comments. Comments in Python  # character start until the actual end of the line (Annotation - author used herein to represent an actual physical line editor transducer row instead wrap). Comments can start from the first line, it can also blank or after the code, but does not appear in the string. Text string  # of characters merely represent  # . Comments in the code are not to be interpreted Python, entry example when you can ignore them.

I point to learn more exciting content to learn

The following 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 The Python as a Calculator

Let's try some simple Python commands. Start the interpreter and wait for the primary prompt  >>> appears (not required for a long time).

 

3.1.1. Digital

Interpreter behave like a simple calculator: you can enter some of its expressions, it will give a return value. Expression syntax is straightforward: operators  +, -, * and  / other languages (for example: Pascal or C); parentheses ( ()) for a packet. E.g:

>>> 2 + 2
4
>>> 50 - 5*6
20
>>> (50 - 5*6) / 4
5.0
>>> 8 / 5  # division always returns a floating point number
1.6

Integer (e.g., 2, ,  4type) 20 is  int , with the fractional part of the number (e.g., 5.0, )  1.6is a type of  a float . Later in this tutorial we'll see more about digital type.

Division ( /) always returns a floating-point number. To use  floor division  and get integer results (any fractional part discarded), you can use the  // operator; you can calculate the number of I use %

>>> 17 / 3  # classic division returns a float
5.666666666666667
>>>
>>> 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

By Python, it may also be used  ** operators calculated power power  [1] :

>>> 5 ** 2  # 5 squared
25
>>> 2 ** 7  # 2 to the power of 7
128

Equal sign (  '=' ) used to assign values to variables. After this assignment, before the next prompt will not have any results showed that:

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

Variables must be "defined" (assigned) before use, otherwise it will go wrong:

>>> # try to access an undefined variable
... n
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'n' is not defined

Complete floating support; mixed integer and floating point calculation, the floating-point number is converted to an integer:

>>> 3 * 3.75 / 1.5
7.5
>>> 7.0 / 2
3.5

Interactive mode, the most recent expression of a value assigned to the variable  _. So that we can use it as a desk calculator, it is convenient for continuous computing, 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 the user. Do not try to assign it - you would create an independent local variable with the same name, which shields the system built-in variable magic effect.

In addition  int  and  a float , the Python also supports other digital types, e.g.  Decimal  and  Fraction . Python is also built-in support  complex , suffix  j , or  J represents an imaginary number part (e.g., 3+5j).

I point to learn more exciting content to learn

3.1.2. String

Compared numbers, Python also provides a string that can be expressed in several different ways. They may be enclosed in single quotes ( '...') or double quotation mark ( "...") identified  [2] . It 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 will be in quotation marks, special characters with backslash. Although it may seem input and not the same, but the two strings are equal. If the string is only a single quote and no double quotes, use double quotes, single quotes or references. print ()  function to generate a more readable output, it will save the print marks and special characters escaped after:

>>> '"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 the character in front of you with is treated as a special character, you can use  the original string , it is to add one before the first quotation mark  r:

>>> print('C:somename')  # here n means newline!
C:some
ame
>>> print(r'C:somename')  # note the r before the quote
C:somename

Text strings can be divided into a plurality of rows. One method is to use the three quoted: """...""" or  '''...'''. Newline end of the line will be automatically included in the string, but may add to the end of the line to avoid this behavior. The following example: backslash may be used as a continuous string ending row, which represents the content of a subsequent line of upper and lower bank logic:

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

Produces the following output (note, not the start of the first line):

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

The string can  + concatenation operator (stick together), may be formed of  * repeating said:

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

Automatic two adjacent text strings together. :

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

It is only for two strings of text, string expression can not be used:

>>> 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 connect more than one variable or a variable connection and a text string, use  +:

>>> prefix + 'thon'
'Python'

This feature is particularly useful when you want to cut a long string of points:

>>> text = ('Put several strings within parentheses '
            'to have them joined together.')
>>> text
'Put several strings within parentheses to have them joined together.'

String can also be intercepted (retrieved). Similar to C, the first character string index is 0. Python is no 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'

Indexes can also be negative, which would lead to counting from the right. E.g:

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

Please note that -0 is actually 0, so it does not cause counting from the right.

In addition to the index, also supports  slices . Index used to obtain a single character, sliced  so that 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 contain characters starting, does not contain a character at the end. This makes  s[:i] + s[i:] is always equal  s:

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

Slice index has a useful default value; omitted defaults to zero the first index, the second index omitted default size of the string sections. :

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

There is a way to easily remember slice works: when the index is sliced in two characters  between  . Index of the first character to the left is 0, and a length of  n  right boundary index of the last character string of which is  n . E.g:

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

Text index point is given the first row of numbers in the string 0 ... 6. The second line gives the corresponding negative indices. Slice from  i  to  j  all characters between the two designated boundary values. I point to learn more exciting content to learn

For non-negative indices, if up and down within the boundary, the length of a slice is the difference between the two indexes. For example, word[1:3] a 2.

Attempt to use much of the index results 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 gracefully handle that can be pointless slice indices: one index value is too large (i.e., greater than the actual index value string length) will be replaced by the actual length of the string, when the upper boundary of the boundary ratio is large (i.e., the left sections value is greater than the right value) returns an empty string:

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

Python string can not be changed - they are  immutable  . Therefore, the position assigned to the index of the string 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'

Built-in function  len ()  Returns a string length:

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

See also

Text Sequence Type — str

String is  a sequence type  example, they support the common operation of this type.

String Methods

Strings and Unicode strings support a large number of methods for basic transformations and searching.

String Formatting

It described herein using  str.format ()  information formatted string.

String Formatting Operations

Described herein old string formatting operations, and string are Unicode strings  % called when the left operand of the operator.

 

3.1.3. List

Several Python  complex  data type used to represent other values. The most common is the  List  (lists), comma separated values between brackets which can be written one. Elements of the list need not be of the same type:

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

Like the string (and all the other built-in  sequence  types), as the list 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 operation returns a new list of elements contained in the request. This means that the following sections operation returns a list of new (light) Copies:

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

The list also supports connections such operations:

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

Unlike  immutable  strings, lists is  variable , which allows to modify 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 use the  append() method  (later we'll see more about the method list) to add new elements to the end of the list:

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

Sections can also be assigned to this operation can change the size of the list, or empty 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
[]

Built-in function  len ()  also applies to lists:

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

Allows nested list (to create a list containing a list of the other), 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 in programming

Of course, we can use Python to complete more complex than two plus two tasks. For example, we can generate a write  Fibonacci  program sequence, as follows:

>>> # 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  b also won the new values 0 and 1 the last line used once.

    In this demonstration, variable assignment before, the right of first complete the calculation. Expression on the right of left to right.

  • Condition (here  b < 10 ) is to true,  the while  loop is executed. In Python, like C, or non-zero integer is true; 0 is false. Condition may be a string or list, in fact, may be any sequence;

    All non-zero length is true, empty sequences are false. The test sample is a simple comparison. Standard comparison operator and the same < C:  > ,  == ,  <=, ,  >= and  !=.

  • Loop  body  is  indented  : indentation is Python organization method statement. Python (also) do not provide an integrated line editing, so you have to input TAB or a space for each contraction.

    In practice I suggest you find a text editor to enter complex Python programs, most text editors provide automatic indentation. During interactive input compound statement, you must enter a blank line at the end to identify the end (since the parser can not guess what line you enter is the last row), each row should be noted that the same statement block must be indented the same the number of blank.

  • Keywords  print ()  value of the expression statement given output. It controls multiple expressions and strings output for the string you want (as we did in the previous example in the calculator).

    When not quoted strings print, insert a space between every two children, so you can format made very beautiful, like this:

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

    By the end of a comma can disable the output line break:

    >>> 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] Because  ** a higher priority than  -, it  -3**2 will be interpreted as  -(3**2) and the result is  -9. To avoid this and to get  9that you can use  (-3)**2.
[2] Unlike other languages, special characters, for example,  n in single quotation marks ( '...') and double quotes ( "..."it has the same meaning) in the. The only difference between the two is in single quotation marks, you do not need to escape  " (but you must escape  ' ), and vice versa.
Published 29 original articles · won praise 9 · views 30000 +

Guess you like

Origin blog.csdn.net/HAOXUAN168/article/details/104087311