Python Basics -- Tutorial (1)

Python 3.9.16
Python official documentation

Python standard library

Pythonis an easy-to-learn, powerful programming language. It has efficient high-level data structures and a simple but effective object-oriented programming approach . PythonThe elegant syntax and dynamic typing, as well as its interpretability, make it an ideal language for scripting and rapid application development in many areas on most platforms.

The Python interpreter and extensive standard library are freely available in source or binary form for all major platforms, available from the Python website at https://www.python.org/ , and can be freely distributed. The same site also contains distributions and pointers to many free third-party Python modules, programs, and tools, as well as other documentation.

The Python interpreter can be easily extended with new functions and data types implemented in C or C++ (or other languages ​​callable from C) . Python is also suitable as an extension language for customizable applications.

This tutorial introduces the reader informally to the fundamental concepts and features of the Python language and system. There is a Python interpreter to help you do it, but all examples are self-contained, so this tutorial can also be read offline.

See the Python Standard Library for descriptions of standard objects and modules . The Python Language Reference gives a more formal definition of the language. To write extensions in C or C++, read Extending and Embedding the Python Interpreter and the Python/C API Reference Manual . There are also several books that cover Python in depth.

This tutorial does not attempt to comprehensively cover every feature, or even every commonly used feature. Instead, it introduces many of Python's most noteworthy features and will give you a good sense of the style and flavor of the language. After reading, you'll be able to read and write Python modules and programs, and you'll be ready to learn more about the various Python library modules described in the Python Standard Library .

The Glossary is also worth a look.

1. Appetizer

If you do a lot of work on your computer, eventually you'll find some tasks you want to automate. For example, you might want to perform a search and replace on a large number of text files, or rename and rearrange a bunch of photo files in complex ways. Maybe you want to write a small custom database, or a specialized GUI application, or a simple game.

If you're a professional software developer, you may have to use several C/C++/Java libraries, but find the usual write/compile/test/recompile cycle too slow. Maybe you're writing a test suite for such a library and find writing test code a tedious task. Or, you may have already written a program that can use an extension language, and you don't want to design and implement an entirely new language for your application.

Python is the language for you.

You could write Unix shell scripts or Windows batch files for some of these tasks, but shell scripts are best at moving files and changing textual data, not so well suited for GUI applications or games. You can write a C/C++/Java program, but even a first draft takes a lot of development time. Python is easier to use, available on Windows, macOS, and Unix operating systems, and will help you get your work done faster.

Python is easy to use, but it's a true programming language that provides more structure and support for larger programs than shell scripts or batch files. On the other hand, Python also offers more error checking than C, and being a very high-level language, it has built-in advanced data types such as flexible arrays and dictionaries. Due to its more general data types, Python is applicable to a much larger problem domain than Awk or even Perl, but many things are at least as simple in Python as they are in these languages.

Python allows you to split programs into modules that can be reused in other Python programs . It comes with a large collection of standard modules that you can use as the basis of your programs - or as examples to start learning Python programming. Some of these modules provide file I/O, system calls, sockets, and even interfaces to GUI toolkits such as Tk.

Python is an interpreted language which saves a lot of time during program development as there is no need for compilation and linking . The interpreter can be used interactively, which makes it easy to experiment with language features, write one-off programs, or test functionality during bottom-up program development. It's also a handy desktop calculator.

2. Use the Python interpreter

2.1. Invoking the interpreter

The location where the Python interpreter is normally installed /usr/local/bin/python3.9; will be /usr/local/binplaced in the search path of Unix shells and can be started by typing:

python3.9

/usr/local/pythonis a popular alternative position

Entering an end-of-file character (yes on Unix Control-D, yes on Windows Control-Z) at the main prompt causes the interpreter to exit with a zero exit status. If that doesn't work, you can exit the interpreter by typing: quit().

On systems that support the GNU Readline library, the interpreter's line editing features include interactive editing, history replacement, and code completion. Perhaps the quickest way to see if command-line editing is supported is to type in the first Python prompt you get Control-P. If it beeps, you can do command-line editing; see the appendix for an introduction to the interactive input editing and history substitution keys . If nothing appears, or if ^Pa response is obtained, command-line editing is unavailable; you can only use backspace to delete characters from the current line.

The interpreter operates somewhat like a Unix shell: when invoked with standard input connected to a tty device, it reads and executes commands interactively; when invoked with a filename argument or with a file as standard input, it reads and executes commands from that The file is read and the script executed.

The second way to start the interpreter ispython -c command [arg] ... that it executes the statements in the command, similar to the shell's -coptions. Since Python statements often contain spaces or other shell-specific characters, it is generally recommended to commandenclose them in single quotes .

Some Python modules are also available as scripts . can be used python -m module [arg] ..., which executes the module's source file as if you had spelled its full name on the command line.

When working with script files, it is sometimes useful to be able to run the script and enter interactive mode afterwards . This can be achieved by passing it before the script -i.

All command line options are described in Command Line and Environment .

2.1.1 Parameter passing

When the interpreter knows the script name and other parameters, the script name and other parameters will be converted into a list of strings and assigned to variables sysin the module . argvYou can import sysaccess the list by executing . sys.argv[0]The length of the list is at least 1; an empty string when no script and arguments are given . When the script name is ' -' (indicating standard input), sys.argv[0]it is set to ' -'. When using the -c command, sys.argv[0]it is set to ' -c'. When using -m module, sys.argv[0]set to the full name of the module being located. Options found after -c command or -m module are not used by the Python interpreter's option processing, but are left to the command or module being processed sys.argv .

2.1.2 Interactive mode

We say that the interpreter is in interactive mode ( ) when a command is read from a tty interactive mode. In this mode, it primary promptprompts the next command with the main prompt ( ), usually three greater-than signs ( >>>); for continuous lines, it secondary promptprompts with the secondary prompt ( ), which defaults to three dots ( ). Before printing the first prompt, the interpreter prints a welcome message stating its version number and copyright notice:

ubuntu@VM-0-13-ubuntu:~$ python3
Python 3.10.6 (main, Mar 10 2023, 10:55:28) [GCC 11.3.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>>

Consecutive lines are required when entering a multi-line structure. As an example, look at this ifstatement:

>>> the_world_is_flat = True
>>> if the_world_is_flat:
...     print("Be careful not to fall off!")
...
Be careful not to fall off!

2.2 Interpreter and its environment

2.2.1 Source Code Encoding

By default, Python source files are treated as UTF-8 encoded . In this encoding, characters from most of the world's languages ​​can be used in both string literals, identifiers, and comments -- although the standard library only uses ASCII characters for identifiers, which is what any portable code should follow agreement . To display all these characters correctly, the editor must recognize that the file is in UTF-8 format and must use a font that supports all the characters in the file.

To declare a non-default encoding, a special comment line should be added as the first line of the file . The syntax is as follows:

# -*- coding: encoding -*-

where encoding is one of the valid codecs ( codecs ) supported by Python.

For example, to declare the use of Windows-1252 encoding, the first line of the source code file should be:

# -*- coding: cp1252 -*-

An exception to the first-line rule is when the source code begins with a UNIX "shebang" line. In this case, the encoding declaration should be added to the second line of the file. For example:

#!/usr/bin/env python3
# -*- coding: cp1252 -*-

On Unix, the Python 3.x interpreter, by default, is not pythoninstalled with an executable named python , so it does not conflict with a concurrently installed python 2.x executable.

3. An informal introduction to Python

In the following example, input and output are distinguished by the presence or absence of a prompt ( >>>and ): To repeat the example, everything after the prompt must be entered when the prompt appears; lines that do not begin with the prompt is output from the interpreter. Note that in the example, the secondary prompt on the line itself means that you must type a blank line; used to end multi-line commands.

You can >>>toggle the display of prompts and output by clicking in the upper right corner of the example box. If you hide the prompts and output in the example, then you can easily copy and paste the input lines into the interpreter.

Many examples in this manual, even those entered at the interactive prompt, contain comments. Comments in Python #start with a hash character and extend to the end of the physical line. Comments can appear at the beginning of a line or after whitespace or code, but not within string literals . A hash character in a string literal is just a hash character. Since comments are meant to clarify code and not be interpreted by Python, they can be omitted when typing 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."

3.1 Using Python as a calculator

Let's try some simple Python commands. Start the interpreter and wait for the main prompt >>>. (It shouldn't take long.)

3.1.1 Numbers

The interpreter is like a simple calculator: you can type an expression into it, and it will write out the value. The expression syntax is simple: the operators +, -, *and /are just like in most other languages ​​(for example, Pascal or C); parentheses ( ()) can be used for grouping. For example:

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

The type of integer (such as 2, 4, 20) is int , and the type of fractional part (such as 5.0, 1.6) is float . We'll see more about numeric types later in this tutorial.

Division( /) always returns a floating point number . To do floor division and get an integer result (discarding any decimal results), you can use //the operator; to calculate the remainder, you can 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  # floored quotient * divisor + remainder
17

In Python, **operators can be used to calculate exponentiations:

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

Because **of the higher precedence than -, -3**2will be interpreted as -(3**2), so the result is -9. To avoid this and get 9, you can use (-3)**2.

The equals sign ( =) is used to assign values ​​to variables . After that, no results are displayed until the next interactive prompt:

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

If a variable has not been "defined" (assigned), trying to use it will give you an error:

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

It fully supports floating-point numbers ; operators with mixed-type operands convert integer operands to floating-point numbers:

>>> 4 * 3.75 - 1
14.0

In interactive mode, the last printed expression is assigned to the variable _. This means that when you're using Python as a desktop calculator, it's a bit easier to continue calculating, for example:

>>> tax = 12.5 / 100
>>> price = 100.50
>>> price * tax
12.5625
>>> price + _
113.0625
>>> round(_, 2)
113.06

This variable should be considered read-only by the user . Don't assign it explicitly - you'll create a separate local variable of the same name, masking the built-in variable with its magical behavior.

In addition to int and float , Python also supports other types of numbers, such as Decimal and Fraction . Python also has built-in support for complex numbers , and uses the jor Jsuffix to denote the imaginary part (eg 3+5j) .

3.1.2 Strings

In addition to numbers, Python can also manipulate strings, which can be represented in several ways . They can be enclosed in single quotes ( '…') or double quotes ( ), with the same result 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," they said.'
'"Yes," they said.'
>>> "\"Yes,\" they said."
'"Yes," they said.'
>>> '"Isn\'t," they said.'
'"Isn\'t," they said.'

In the interactive interpreter, output strings are enclosed in quotes and special characters are escaped with backslashes . While this sometimes looks different from the input (closing quotes may change), the two strings are equivalent. If the string contains single quotes but not double quotes, enclose the string in double quotes, otherwise enclose the string in single quotes. The print() function produces more readable output by omitting quotes and printing escape and special characters:

>>> '"Isn\'t," they said.'
'"Isn\'t," they said.'
>>> print('"Isn\'t," they said.')
"Isn't," they 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 don't want \characters starting with to be interpreted as special characters, you can use raw strings, adding one before the first quote r:

>>> 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 literals can span multiple lines . One way is to use triple quotes: """..."""or '''...'''. \Line endings are automatically included in strings, but this can be prevented by appending them . Example below:

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

Strings can +be concatenated (glued together) with operators, and *repeated with:

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

Adjacent two or more string literals (string literals, that is, literal values ​​enclosed between quotation marks) are automatically concatenated.

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

This function is especially useful when you want to break long strings:

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

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

>>> prefix = 'Py'
>>> prefix 'thon'  # can't concatenate a variable and a string literal
  File "<stdin>", line 1
    prefix 'thon'
                ^
SyntaxError: invalid syntax
>>> ('un' * 3) 'ium'
  File "<stdin>", line 1
    ('un' * 3) 'ium'
                   ^
SyntaxError: invalid syntax

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

>>> prefix + 'thon'
'Python'

Strings can be indexed (indexed, subscript), the index of the first character is 0 . 没有单独的字符类型; A character is a string of size 1:

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

Indexes can also be negative, counting from the right:

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

Note that negative signs start at -1 because -0 is the same as 0.

In addition to indexing, 切片( slicing) is also supported. Indexing is used to get individual characters, but slicing allows you to get substrings:

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

There are useful defaults for slice indices; an omitted first index defaults to zero, and an omitted second index defaults to the size of the string being sliced.

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

Note that beginnings are always included and endings are always excluded. This ensures that s[:i] + s[i:]is always equal to s:

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

One way to remember how slicing works is to think of the indices as pointing between characters , with the first character's left edge numbered 0. Then, the right edge of the last character of a string containing n characters has index n, for example:

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

The first row of numbers gives 0…6the position of the index in the string; the second row gives the corresponding negative index. A slice from ito consists of all characters between the edges jlabeled iand respectively.j

For non-negative indices, the length of the slice is the difference between the indices if both indices are within bounds . For example, word[1:3]the length of 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

However, out-of-range slice indices are handled gracefully when used for slices :

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

Python strings cannot be changed - they are immutable . Therefore, assigning a value to an indexed position in a string results in an error:

>>> word[0] = 'J'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'str' object does not support item assignment
>>> word[2:] = 'py'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
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

Text Sequence Type — str
string is sequence typesan example of a sequence type ( ) and supports common operations supported by these types.
String Methods
Strings support a large number of methods for basic transformations and searches.
Formatted string literals
have string literals embedded in expressions.
Format String Syntax
uses str.format() to format string information.
printf-style String Formatting
describes in more detail here the %old formatting operation invoked when a string is the left operand of an operator.

3.1.3 List

Python knows many compound data types for combining other values ​​together. The most general is a list, which can be written as a list of comma-separated values ​​(items) between square brackets ( list). Lists may contain items of different types, but usually the items are all of the same type .

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

Like strings (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 slice operations return a new list containing the requested elements . This means that the following slice returns a shallow copy of the list :

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

Lists also support operations like concatenation:

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

Unlike strings, which are immutable , lists are a mutable type , that is, their contents can be changed :

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

append()You can also add new items at the end of the list by using the method (we'll see more about 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]

Assignment to slices is also possible, which can even change the size of the list or clear it entirely:

>>> 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 works on lists:

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

Lists can be nested (create lists that contain 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 First steps in programming

Of course, we can use Python to accomplish more complex tasks than adding two to two. For example, we can write the initial subsequence of the Fibonacci sequence like this:

>>> # Fibonacci series:
... # the sum of two elements defines the next
... a, b = 0, 1
>>> while a < 10:
...     print(a)
...     a, b = b, a+b
...
0
1
1
2
3
5
8

This example introduces several new features.

  • The first line contains multiple assignments ( multiple assignment): variables aand bget new values 0​​and at the same time 1. Used again in the last line, it proves that the expression on the right is evaluated first, before any assignment occurs. Expressions on the right are evaluated from left to right .
  • The while loop executes as long as the condition (here: a < 10) remains true . In Python, as in C, any non-zero integer value is true; 0 is false. Conditions can also be string or list values, and indeed any sequence; any sequence of non-zero length is true, and an empty sequence is 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 with : 缩进是Python对语句进行分组的方式. At the interactive prompt, you must type a tab or space for each indented line. In practice, you'll use a text editor to prepare more complex input for Python ; all decent text editors have auto-indentation. When a compound statement is inserted, it must be followed by a blank line to indicate completion (since the parser cannot estimate when you typed the last line). Note that every line within a basic block must be indented by the same amount .
  • The function print() writes the value of the parameter(s). It's different than writing the expression you want (as we did earlier in the calculator example), in the way it can handle multiple arguments, floats, and strings. Strings are printed without quotes, inserting a space 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

print()The keyword arguments endto can be used to avoid newlines after the output, or to end the output with a different string:

>>> a, b = 0, 1
>>> while a < 1000:
...     print(a, end=',')
...     a, b = b, a+b
...
0,1,1,2,3,5,8,13,21,34,55,89,144,233,377,610,987,

4. Process control

In addition to the while statement just introduced , Python also uses flow control statements common in other languages, with some modifications.

4.1 if statement

Perhaps the most well-known statement type is ifthe statement. For example:

x = int(input("Please enter an integer: "))

if x < 0:
    x = 0
    print('Negative changed to zero')
elif x == 0:
    print('Zero')
elif x == 1:
    print('Single')
else:
    print('More')

There can be zero or more elif sections, else sections are optional. The keyword ' elif ' is else if short for ' ' and is used to avoid excessive indentation. Sequences are a substitute for or statements if … elif … elif …in other languages .switchcase

4.2 for statement

The for statement in Python is slightly different than what you might use in C or Pascal. Python's for statement does not always iterate over an arithmetic sequence of numbers (such as Pascal), nor does it allow users to define iteration steps and stop conditions (such as C language), Python's statement iterates over any sequence (list or string for) items, in the order in which they appear in the sequence . For example (no pun intended):

# Measure some strings:
words = ['cat', 'window', 'defenestrate']
for w in words:
    print(w, len(w))

Code that modifies a collection while iterating over the same collection can be difficult to get right. Instead, it is often more straightforward to iterate over a copy of the collection or create a new one:

# Strategy:  Iterate over a copy
for user, status in users.copy().items():
    if status == 'inactive':
        del users[user]

# Strategy:  Create a new collection
active_users = {
    
    }
for user, status in users.items():
    if status == 'active':
        active_users[user] = status

4.3 range() function

If you really need to iterate over a set of numbers, built-in functions range()come in handy. It generates arithmetic progressions:

for i in range(5):
    print(i)

The given endpoint was never part of the generated sequence ; range(10)a value of 10 is generated, which is a legal index for a sequence item of length 10. You can let rangestart at another number, or specify a different increment (even negative; sometimes this is called a "step"):

list(range(5, 10))


list(range(0, 10, 3))


list(range(-10, -100, -30))

To iterate over the indices of a sequence, you can combine range() and len() as follows:

a = ['Mary', 'had', 'a', 'little', 'lamb']
for i in range(len(a)):
    print(i, a[i])

In most cases, however, it is convenient to use the enumerate() function, see Looping Techniques .

    a = ['Mary', 'had', 'a', 'litle', 'lamb']
    for i, j in enumerate(a):
        print(i, j)

If you just print a range, a strange thing happens:

print(range(10))
// range(0, 10)

In many ways, range()the returned object behaves as if it is a list, but it is not. It's an object, and when you iterate over it, it returns the desired sequence of consecutive items, but it doesn't really create a list, so it saves space.

We say that such objects are iterable , that is, suitable as targets for functions and constructs that expect successive items from them until exhausted . We've seen forthat statements are such a structure, and an example of a function that accepts an iterable is sum():

sum(range(4))  # 0 + 1 + 2 + 3

Later we will see more functions that return iterables and accept iterables as parameters . In the data structures chapter, we will discuss list() in more detail .

4.4 break and continue statements in loops, and else clauses

The break statement, like in C, breaks out of the innermost foror loop.while

Loop statements can have elseclauses; executed when the loop terminates due to exhaustion of the iterable (use for) or when the condition becomes false (use while), but breaknot when the loop is terminated by the statement . An example is the following loop, which searches for prime numbers:

for n in range(2, 10):
    for x in range(2, n):
        if n % x == 0:
            print(n, 'equals', x, '*', n//x)
            break
    else:
        # loop fell through without finding a factor
        print(n, 'is a prime number')

2 is a prime number
3 is a prime number
4 equals 2 * 2
5 is a prime number
6 equals 2 * 3
7 is a prime number
8 equals 2 * 4
9 equals 3 * 3

(Yes, this is correct code. Look closely: elseclauses belong in forloops, not ifstatements.)

ifWhen used with loops, clauses elsehave more in common with the clauses of the try statement than with statements: the clauses of the statement run when no exception occurs, while the clauses of the loop run when none occur . For more information on statements and exceptions, see Handling Exceptions .elsetryelseelsebreaktry

The continue statement, also borrowed from C, continues with the next iteration of the loop:

for num in range(2, 10):
    if num % 2 == 0:
        print("Found an even number", num)
        continue
    print("Found an odd number", num)

4.5 pass statement

The pass statement does nothing. It is used when a statement is required syntactically, but no action is required by the program . For example:

while True:
    pass  # Busy-wait for keyboard interrupt (Ctrl+C)

This is usually used to create a minimal class:

class MyEmptyClass:
    pass

Another passplace it can be used is as a placeholder for the body of a function or condition when writing new code, allowing you to think at a more abstract level. pass is silently ignored:

def initlog(*args):
    pass   # Remember to implement this!

4.6. Defining functions

We can create a function that writes the Fibonacci sequence to arbitrary bounds:

def fib(n):    # write Fibonacci series up to n
    """Print a Fibonacci series up to n."""
    a, b = 0, 1
    while a < n:
        print(a, end=' ')
        a, b = b, a+b
    print()

# Now call the function we just defined:
fib(2000)
# 0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597

The keyword def introduces a function definition ( function definition). It must be followed by the function name and a parenthesized list of formal parameters. The statements that make up the function body start on the next line and must be indented.

The first statement of a function body can be a string literal; this string literal is the function's documentation string, ordocstring . (More information on docstrings can be found in the Docstrings section.) Some tools use docstrings to automatically generate online or print documentation, or to let users interactively walk through code; include docstrings in the code you write Skewing is good practice, so make it a habit.

Execution( execution) of a function introduces a new symbol table for the function's local variables . More precisely, all variable assignments ( variable assignments) in a function store values ​​in the local symbol table; whereas variable references ( variable references) are first looked up in the local symbol table, then in the 外围函数(enclosing function) local symbol table, then Look up in the global symbol table, and finally in the built-in names ( built-in names) table . Therefore, 全局变量和外围函数的变量不能在函数内直接赋值(unless global variables are named in the global statement, or variables of enclosing functions are named in nonlocal ), although they can be referenced.

The actual formal parameters of a function call (actual parameters, arguments) are introduced into the local symbol table of the called function at call time; therefore, parameters are passed using call by value (where the value is always an object reference, not the object's call by valuevalue ). When a function calls another function, or recursively calls itself, a new local symbol table is created.

A function definition associates a function name with a function object in the current symbol table . The interpreter recognizes the object pointed to by this name as a user-defined function. Other names can also point to the same function object and can also be used to access the function:

fib

f = fib
f(100)

In other languages, you might object fibto not being a function, but a procedure, since it doesn't return a value. In fact, even functions without a return statement return a value, albeit a rather boring one. This value is called None(it's a built-in name) . NoneThe interpreter normally suppresses writing of a value if it is the only value written. If you really want to use print() , you can see it:

fib(0)
print(fib(0))

Writing a function that returns a list of numbers in the Fibonacci sequence, rather than printing them out, is as simple as:

def fib2(n):  # return Fibonacci series up to n
    """Return a list containing the Fibonacci series up to n."""
    result = []
    a, b = 0, 1
    while a < n:
        result.append(a)    # see below
        a, b = b, a+b
    return result

f100 = fib2(100)    # call it
f100                # write the result

As usual, this example demonstrates some new Pythonfeatures:

  • The return statement returns a value from a function. returnReturn without an expression argument None. Execution to the end of the function also returns None.
  • statement result.append(a)calls resulta method of the list object. A method is a function that "belongs" to an object, named obj.methodname, where objis some object (possibly an expression), and methodnameis the method name defined by the object's type. Different types define different methods. Methods of different types can have the same name without ambiguity . (You can define your own object types and methods using classes, see Classes ) The method shown in the example append()is defined for list objects; it adds a new element to the end of the list. In this case, it's equivalent result = result + [a], but more efficient.

4.7 More on defining functions

It is also possible to define functions with a variable number of arguments . There are three forms, which can be used in combination .

4.7.1 Default parameter values

The most useful form is to specify default values ​​for one or more parameters . This creates a function that can be called with fewer arguments than the definition allows. For example:

def ask_ok(prompt, retries=4, reminder='Please try again!'):
    while True:
        ok = input(prompt)
        if ok in ('y', 'ye', 'yes'):
            return True
        if ok in ('n', 'no', 'nop', 'nope'):
            return False
        retries = retries - 1
        if retries < 0:
            raise ValueError('invalid user response')
        print(reminder)

This function can be called in several ways:

  • Only mandatory parameters are given:ask_ok('Do you really want to quit?')
  • Given an optional argument:ask_ok('OK to overwrite the file?', 2)
  • Or even given all arguments:ask_ok('OK to overwrite the file?', 2, 'Come on, only yes or no!')

This example also introduces the in keyword. This tests whether a sequence contains a certain value.

Default values defining scope​​are evaluated at the point of function definition within the defining scope ( ) , so

i = 5

def f(arg=i):
    print(arg)

i = 6
f()
# 将打印5。

Important warning : 默认值只计算一次. This makes a difference when the default value is a mutable object such as a list, dictionary, or instance of most classes. For example, the following function accumulates the arguments passed to it on subsequent calls:

def f(a, L=[]):
    L.append(a)
    return L

print(f(1))
print(f(2))
print(f(3))

This will print:

[1]
[1, 2]
[1, 2, 3]

If you don't want to share the default value between subsequent calls, you can write the function like this:

def f(a, L=None):
    if L is None:
        L = []
    L.append(a)
    return L

4.7.2 Keyword arguments

Functions can also kwarg=valuebe called with keyword arguments of the form. For example, the following function:

def parrot(voltage, state='a stiff', action='voom', type='Norwegian Blue'):
    print("-- This parrot wouldn't", action, end=' ')
    print("if you put", voltage, "volts through it.")
    print("-- Lovely plumage, the", type)
    print("-- It's", state, "!")

Accepts one required parameter ( voltage) and three optional parameters ( state, action, and type). This function can be called in any of the following ways:

parrot(1000)                                          # 1 positional argument
parrot(voltage=1000)                                  # 1 keyword argument
parrot(voltage=1000000, action='VOOOOOM')             # 2 keyword arguments
parrot(action='VOOOOOM', voltage=1000000)             # 2 keyword arguments
parrot('a million', 'bereft of life', 'jump')         # 3 positional arguments
parrot('a thousand', state='pushing up the daisies')  # 1 positional, 1 keyword

But all the following calls are invalid:

parrot()                     # required argument missing
parrot(voltage=5.0, 'dead')  # non-keyword argument after a keyword argument 
							 # 关键字参数后的非关键字参数

parrot(110, voltage=220)     # duplicate value for the same argument
parrot(actor='John Cleese')  # unknown keyword argument

In a function call, keyword arguments must immediately follow positional arguments . All keyword arguments passed must match one of the arguments accepted by the function (e.g. actor is not a valid argument for the parrot function), their order is not important . This also includes non-optional parameters (eg parrot(voltage=1000)also valid). No parameter can accept a value more than once. Here is an example that fails due to this limitation:

def function(a):
    pass

function(0, a=0)

###########
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: function() got multiple values for argument 'a'

When the last formal parameter of the form **nameis present, it receives a dictionary (see Mapped Types - dict ) containing all but those corresponding to the formal parameter关键字参数 . This can be *nameused in conjunction with the formal parameter of the form (described in the next subsection), which accepts a tuple位置参数 containing the parameters outside of the formal parameter list . ( *namemust appear **namebefore.) For example, if we define a function like this:

def cheeseshop(kind, *arguments, **keywords):
    print("-- Do you have any", kind, "?")
    print("-- I'm sorry, we're all out of", kind)
    for arg in arguments:
        print(arg)
    print("-" * 40)
    for kw in keywords:
        print(kw, ":", keywords[kw])

It can be called like this:

cheeseshop("Limburger", "It's very runny, sir.",
           "It's really very, VERY runny, sir.",
           shopkeeper="Michael Palin",
           client="John Cleese",
           sketch="Cheese Shop Sketch")

Of course, it prints:

-- Do you have any Limburger ?
-- I'm sorry, we're all out of Limburger
It's very runny, sir.
It's really very, VERY runny, sir.
----------------------------------------
shopkeeper : Michael Palin
client : John Cleese
sketch : Cheese Shop Sketch

Note that the order in which keyword arguments are printed is guaranteed to match the order in which they were supplied in the function call.

4.7.3 Special parameters

By default, arguments can be passed to Python functions either positionally or explicitly via keywords . For readability and performance, it makes sense to restrict how parameters are passed so that a developer only needs to look at the function definition to determine whether items are passed positionally, positionally or keyword, or by keyword.

A function definition might look like this:

def f(pos1, pos2, /, pos_or_kwd, *, kwd1, kwd2):
      -----------    ----------     ----------
        |             |                  |
        |        Positional or keyword   |
        |                                - Keyword only
         -- Positional only

where /and *are optional . If used, these symbols indicate the type of the formal parameter by the way the actual parameter is passed to the function: positional only, positional or keyword only, and keyword only. Keyword arguments are also known as named arguments .

4.7.3.1 Positional-or-Keyword parameter

If /and *do not appear in the function definition, arguments can be passed to the function either positionally or as keywords.

4.7.3.2 Positional-Only parameters

Looking at it in more detail, certain parameters can be marked as positional-only. If it is a positional type, the order of the parameters is important, and parameters cannot be passed by keyword . Positional-only parameters are preceded /by a (forward slash). /Used to logically separate positional-only parameters from other parameters. If none in the function definition /, there are no positional arguments.

/Subsequent arguments can be position -or-keywordor keyword-only.

4.7.3.3 Keyword-Only parameter

To mark a parameter as keyword-only, indicating that the parameter must be passed as keyword-only, place it before the first keyword-only parameter in the parameter list *.

4.7.3.4 Examples of functions

Consider the following sample function definition, paying close attention /and *marking:

def standard_arg(arg):
    print(arg)

def pos_only_arg(arg, /):
    print(arg)

def kwd_only_arg(*, arg):
    print(arg)

def combined_example(pos_only, /, standard, *, kwd_only):
    print(pos_only, standard, kwd_only)

The first function definition, standard_arg, is the most familiar form, with no restrictions on the calling convention, and arguments can be passed positionally or by keyword:

standard_arg(2)

standard_arg(arg=2)

The second function pos_only_argis restricted to only use positional parameters, because the function definition has a /:

pos_only_arg(1)


pos_only_arg(arg=1)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: pos_only_arg() got some positional-only arguments passed as keyword arguments: 'arg'

The third function only allows keyword arguments denoted kwd_only_argsby in the function definition :*

kwd_only_arg(3)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: kwd_only_arg() takes 0 positional arguments but 1 was given

kwd_only_arg(arg=3)

The last one uses all three calling conventions in the same function definition:

>>> combined_example(1, 2, 3)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: combined_example() takes 2 positional arguments but 3 were given

>>> combined_example(1, 2, kwd_only=3)
1 2 3

>>> combined_example(1, standard=2, kwd_only=3)
1 2 3

>>> combined_example(pos_only=1, standard=2, kwd_only=3)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: combined_example() got some positional-only arguments passed as keyword arguments: 'pos_only'

Finally, consider this function definition, which has a potential conflict between positional arguments nameand namepromising keys:**kwds

def foo(name, **kwds):
    return 'name' in kwds

There is no possible call that would make it return True, because the keyword 'name' is always bound to the first argument. For example:

>>> foo(1, **{
    
    'name': 2})
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: foo() got multiple values for argument 'name'
>>>

But with /(positional arguments), this is possible because it allows nameas positional arguments, 'name'keys as keyword arguments:

def foo(name, /, **kwds):
    return 'name' in kwds
>>> foo(1, **{
    
    'name': 2})
True

In other words, only the names of positional parameters can **kwdsbe used without ambiguity in .

4.7.4 Arbitrary parameter lists

Finally, the least commonly used option is to specify that the function can be called with any number of arguments . These arguments will be packed in a tuple (see Tuples and Sequences ). Zero or more normal arguments may appear before a variable number of arguments.

def write_multiple_items(file, separator, *args):
    file.write(separator.join(args))

Typically, these variadic parameters will come last in the formal parameter list, since they contain all remaining input parameters passed to the function . 出现在*args 参数之后的任何形式参数都是“仅关键字”参数,这意味着它们只能用作关键字而不是位置参数.

>>> def concat(*args, sep="/"):
...     return sep.join(args)
...
>>> concat("earth", "mars", "venus")
'earth/mars/venus'
>>> concat("earth", "mars", "venus", sep=".")
'earth.mars.venus'

4.7.5 Unpacking parameter list

The opposite occurs when the arguments are already in a list or tuple, but need to be unpacked for a function call that expects individual positional arguments . For example, built-in range()functions require separate startand stopparameters. If they cannot be used alone, use *the - operator to write function calls, unpacking arguments from lists or tuples:

>>> list(range(3, 6))            # normal call with separate arguments
[3, 4, 5]
>>> args = [3, 6]
>>> list(range(*args))            # call with arguments unpacked from a list
[3, 4, 5]

In the same way, dictionaries can be **passed keyword arguments using the - operator:

def parrot(voltage, state='a stiff', action='voom'):
    print("-- This parrot wouldn't", action, end=' ')
    print("if you put", voltage, "volts through it.", end=' ')
    print("E's", state, "!")

d = {
    
    "voltage": "four million", "state": "bleedin' demised", "action": "VOOM"}
parrot(**d)

4.7.6 Lambda expressions

Small anonymous functions can be created using the lambda keyword. This function returns the sum of two arguments: lambda a, b: a+b. Lambda functions can be used anywhere a function object is expected . 它们在语法上被限制为单个表达式。从语义上讲,它们只是普通函数定义的语法糖. Like nested function definitions, lambda functions can refer to variables from the containing scope :

>>> def make_incrementor(n):
...     return lambda x: x + n
...
>>> f = make_incrementor(42)
>>> f(0)
42
>>> f(1)
43

The above example uses a lambda expression to return a function. Another usage is to pass a small function as an argument:

>>> pairs = [(1, 'one'), (2, 'two'), (3, 'three'), (4, 'four')]
>>> pairs.sort(key=lambda pair: pair[1])
>>> pairs
[(4, 'four'), (1, 'one'), (3, 'three'), (2, 'two')]

4.7.7 Docstrings

The following are some conventions regarding the content and format of docstrings.

The first line should be a short summary of the purpose of the object . For brevity, 它不应该显式地声明对象的名称或类型, since these can be obtained by other means (unless the name happens to be a verb describing the operation of the function). This line should start with a capital letter and end with a period.

If there are more lines in the docstring, the second line should be empty, visually separating the summary from the rest of the description . The next few lines should be one or more paragraphs describing the object's calling convention, its side effects, etc.

The Python parser does not remove indentation from multiline string literals in Python, so tools that process documentation must remove indentation when needed . This is done using the following conventions. The first non-empty line after the first line of the string determines the amount of indentation for the entire docstring . (We can't use the first line because it's usually adjacent to the string's opening quote, so its indentation isn't apparent in the string literal.) Then remove the indentation with this from all lines of the string starting with " etc. Effective" blank. Lines with less indentation should not appear, but if they do, all their leading whitespace should be removed. The equivalence of whitespace should be tested after expanding tabs (usually 8 spaces).

Here is an example of a multi-line docstring:

def my_function():
    """Do nothing, but document it.

    No, really, it doesn't do anything.
    """
    pass

print(my_function.__doc__)
Do nothing, but document it.

    No, really, it doesn't do anything.

4.7.8 Function annotations

Function Annotations are completely optional metadata information about the types used by user-defined functions (see PEP 3107 and PEP 484 for more information).

Annotations are stored as a dictionary in the function's __annotations__properties and have no effect on any other part of the function. 参数注解is defined by a colon after the parameter name, followed by an expression that evaluates to the value of the annotation . Defined by a literal value followed by an expression between the 返回注释formal parameter list anddef-> the colon denoting the end of the statement . The following example has one required parameter, one optional parameter, and the return value is annotated:

def f(ham: str, eggs: str = 'eggs') -> str:
    print("Annotations:", f.__annotations__)
    print("Arguments:", ham, eggs)
    return ham + ' and ' + eggs

f('spam')

Annotations: {
    
    'ham': <class 'str'>, 'return': <class 'str'>, 'eggs': <class 'str'>}
Arguments: spam eggs
'spam and eggs'

4.8 Intermezzo: coding style

Now that you're about to write longer, more complex Python code, now is a good time to discuss coding style. Most languages ​​can be written (or, more concisely, formatted) in different styles; some are more readable than others. It's always a good idea to make your code easy for others to read, and adopting a good coding style helps a lot with this.

For Python, PEP 8 has become the style guide that most projects follow; it promotes a very readable and eye-pleasing coding style. Every Python developer should read it at some point; here are the most important points excerpted for you:

  • Use 4 spaces for indentation, no tabs.
    4 spaces is a good compromise between small indentation (allows greater nesting depth) and large indentation (easier to read). Tabs are confusing and are best not used.
  • Wrap the lines so they don't exceed 79 characters.
    This helps users with small monitors and makes it possible to have multiple code files side by side on larger monitors.
  • Use blank lines to separate functions and classes, and larger blocks of code inside functions.
  • Put comments on their own lines if possible .
  • Use docstrings .
  • Use spaces around operators and after commas, but not directly inside parenthesis constructs :a = f(1, 2) + g(3, 4)
  • Consistently name your classes and functions ; the convention is to use for classes UpperCamelCase and use for functions and methods lowercase_with_underscores . Always use selfthe name that is the first method argument (see A first Look at Classes for more information on classes and methods).
  • If your code is intended to be used in an international environment, then don't use fancy encodings . Python's default, UTF-8, or even plain ASCII is best in any case.
  • Likewise, don't use non-ascii characters in identifiers if there's little chance that the code will be read or maintained by someone speaking a different language .

Guess you like

Origin blog.csdn.net/chinusyan/article/details/131112303