SoFunction
Updated on 2025-03-04

Introduction to Python Page 4/10


Chapter 4 Process Control
We have seen how to run the process using a while structure. In this chapter, we introduce more control structures. Python has a similar control structure to other languages ​​but is slightly different.

4.1 If statement
The If statement may be the most basic program branch statement. For example:

>>> 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 to multiple elif parts, and the else part is optional. The keyword elif is the abbreviation of else if, which can shorten the length of the statement line. In other languages, switch or case statements can be implemented using if...elif...elif... statement group.

4.2 for statement
The for statement in Python is slightly different from the corresponding statement in C or Pascal that you may be familiar with. Instead of always cycling sequences of numbers like Pascal, nor is it freely controlled by programmers as in C, Python's for loop is to traverse each item in order of occurrence on any kind of sequence (such as lists or strings). For example:

>>> # Calculate the string length:
... a = ['cat', 'window', 'defenestrate']
>>> for x in a:
...     print x, len(x)
... 
cat 3
window 6
defenestrate 12
>>>


Try not to modify the sequence used to control the cycle in the loop body (of course, only variable sequence types such as lists can be modified), so that the program may have problems. If you need this, for example, to copy certain items, you can use a copy of the sequence to control the loop. Fragment marking makes it easy for you to generate copy:

>>> for x in a[:]: # Generate a copy of the entire list
...    if len(x) > 6: (0, x)
... 
>>> a
['defenestrate', 'cat', 'window', 'defenestrate']
>>>


The result is that strings with a length of more than 6 characters in the list are inserted into the beginning of the list.

4.3 range() function
If you really need to loop a column of numbers, you can use the built-in function range(). It generates a list containing sequences of numbers, such as:

>>> range(10)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>>


Note that the given endpoint never appears in the generated list, range(10) generates a list of ten numbers, exactly the respective values ​​of the legal subscript of the sequence of length 10. You can also specify different starting points, or specify different intervals (even negative numbers):

>>> range(5, 10)
[5, 6, 7, 8, 9]
>>> range(0, 10, 3)
[0, 3, 6, 9]
>>> range(-10, -100, -30)
[-10, -40, -70]
>>>


In order to loop over the subscript of the sequence, use range() and len() together as follows:

>>> a = ['Mary', 'had', 'a', 'little', 'lamb']
>>> for i in range(len(a)):
...     print i, a[i]
... 
0 Mary
1 had
2 a
3 little
4 lamb
>>>
 


4.4 Break statement, continue statement and else clause in loop
Just like C language, the break statement jumps out of the innermost for or while loop where it is located, and the continue statement continues to the next loop step.

A loop statement can also have an else clause, and the content is executed when the loop ends normally, but if the loop is popped out with a break statement, the content is not executed. The following example illustrates this usage, in this example, find the prime number:

>>> for n in range(2, 10):
...     for x in range(2, n):
...         if n % x == 0:
...            print n, 'equals', x, '*', n/x
...            break
...     else:
...          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
>>>
 


4.5 pass statement
The pass statement does not perform any operation, and is used when the syntax requires a statement but the program does not need to perform an operation. For example:

>>> while 1:
...         pass # Wait for the keyboard to break
...
 


4.6 Function definition
We can define a function to calculate all Fibonacci sequence values ​​below a certain boundary:

>>> def fib(n):     # Write out all the Fibonacci sequence values ​​below n
...     a, b = 0, 1
...     while b < n:
...           print b,
...           a, b = b, a+b
... 
>>> # Call the function you just defined:
... fib(2000)
 
1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597
>>>


The keyword def starts a function definition, followed by the function name, the formal parameter table in parentheses, ending with a colon. Each statement that constitutes the function body starts from the next line and is indented with a tab character. The first statement of a function can be a string. If so, this string is the document string of the function, referred to as docstring for short. There are some tools that can use document strings to automatically generate printable documents, or allow users to browse code interactively, so it is a good habit to add document strings when programming yourself, and you should develop such a habit.

The function introduces a new symbol table to local variables when executed. All variable assignments in the function are stored in the local symbol table; when referring to a variable, the variable name is first searched from the local symbol table, then searched in the global symbol table, and finally searched from the built-in name. Therefore, global variables cannot be assigned directly in a function (unless global statements are used to explain), but the value of the global variable can be referenced.

The actual parameters of the function call are introduced into the local symbol table of the function, that is, the parameters of the function are called by value. When the function calls other functions, a new symbol table is generated for the function. But strictly speaking, the call of a function is called by reference, because if the parameter is a mutable type, such as a list, changing the content of the formal parameter in the function will cause the content of the actual parameter to be changed (the binding relationship of the actual parameter name is not changed).

Function definition puts the function name into the current symbol table. The value type of the function name is a user-defined function, and this value can be assigned to another name, so that this name also represents the same function. This can be used as a general method of renaming:

 
>>> fib
<function object at 10042ed0>
>>> f = fib
>>> f(100)
1 1 2 3 5 8 13 21 34 55 89
>>>
 


You might say that fib is not a function but a process. Python is like C, and procedures are just functions that do not return values. In fact, strictly speaking, the process also returns a value, which is just a very boring value. This value is called None (this is a built-in name). If the interpreter only needs to display this value during interactive running, it will be ignored and not displayed. If you want to display, you can use the print statement:

 
>>> print fib(0)
None
>>>
 
You can also write a function to return a list of numeric values ​​of the Fibonacci sequence instead of displaying these values:
 
>>> def fib2(n): # Returns the Fibonacci sequence value until n
...     result = []
...     a, b = 0, 1
...     while b < n:
...          (b)                                                   �
...           a, b = b, a+b
...     return result
... 
>>> f100= fib2(100)     #Call
>>> f100
[1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
 
>>>
 


This example also demonstrates a new Python feature: the return statement exits the function and returns a value. Return without return value can exit from the middle of the process, and can also exit from the end of the process. In both cases, None is returned.

Statement (b) calls a method of the list object result. The method is a function that "belongs" to an object, with reference format in which obj is an object (also allowed to be an expression), and methodname is the name of a method defined by the type of the object. Different methods. Different types of methods can use the same name without causing misunderstanding. (You can define your own object types and methods and use classes. This topic will be discussed later in this article). In the example, the append() method of the list object is used, which adds a new element at the end of the list. In this case, this is equivalent to "result = result + [b]", but it is more effective.

4.7 Function Parameters
A function that uses variable number parameters can be defined. There are three such definition methods, which can be used in combination.

4.7.1 Parameter default value
You can specify a default value for one or several parameters. The number of real parameters of the function defined in this way can be smaller when called than when defined. For example:

def ask_ok(prompt, retries=4, complaint='Yes or no, please!'):
    while 1:
        ok = raw_input(prompt)
        if ok in ('y', 'ye', 'yes'): return 1
        if ok in ('n', 'no', 'nop', 'nope'): return 0
        retries = retries - 1
        if retries < 0: raise IOError, 'refusenik user'
        print complaint


When this function is called, you can call it like this: ask_ok('Do you really want to quit?'), or you can call it like this: ask_ok('OK to overwrite the file?', 2). The default value is calculated in the scope of definition when the function is defined, so for example:

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


5 will be displayed.

Note: The default value is calculated only once. This is important to note when the default value is a mutable object such as a list or a dictionary. For example, the following function will accumulate its value in a later call:

def f(a, l = []):
    (a)
    return l
print f(1)
print f(2)
print f(3)
This will print 
 
[1]
[1, 2]
[1, 2, 3]


If you do not want the default value to be preserved in consecutive calls, you can rewrite the function like this:

def f(a, l = None):
    if l is None:
        l = []
    (a)
    return l


4.7.2 Keyword parameters
When calling a function, you can also specify actual parameters like "Keyword = Value", where the keyword is the name of the formal parameter used when defining. For example:

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


It can be called in the following ways:

parrot(1000)
parrot(action = 'VOOOOM', voltage = 1000000)                                                �
parrot('a thousand', state = 'pushing up the daisies')       Position parameters, default values, keywords
parrot('a million', 'bereft of life', 'jump')                                                                                                              �


But the following calling methods are wrong:

 

parrot()                                                                                                                             �
parrot(voltage=5.0, 'dead') # The non-keyword parameter appears after the keyword parameter.
parrot(110, voltage=220)
parrot(actor='John Clese')  # Unknown keyword


Generally speaking, the position parameters in the actual parameter table are first and the keyword parameters are second, and the keyword name must be the formal parameter name. Whether the formal parameters have default values ​​can be called in the form of keyword parameters. Each formal parameter can only correspond to one real parameter at most, so the formal parameter that has been passed into the value from the positional parameter cannot be used as a keyword parameter in the same call.

If there is a formal parameter with a shape of **name in the formal parameter table, this formal parameter can receive a dictionary when called, which contains all keyword parameters that do not match any formal parameter. A special formal parameter such as *name can also be used in the formal parameter table, which will accept a sequence of all positional parameters that cannot be matched. *name can only appear before **name. For example, if the following function is defined:

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 (): print kw, ':', keywords[kw]


You can call it like this:

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


The results show:

-- 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.
----------------------------------------
client : John Cleese
shopkeeper : Michael Palin
sketch : Cheese Shop Sketch


4.7.3 Any number parameters
There can be two special formal parameters behind all famous formal parameters, one named in the form of *args and the other named in the form of **kw. After the function with the *args form formal parameters, when called, it can enter any number of parameters after the normal matching actual parameter table. These parameters form a sequence table and assign it to args formal parameters, and the keyword parameters that cannot be matched form a dictionary to assign it to a kw formal parameters. There can be 0 to more than 2 normal parameters before any numbered parameter. For example:

def fprintf(file, format, *args):
    (format % args)


4.7.4 Lambda Form
Because of many people's requirements, Python has added some common features in functional programming languages ​​and Lisp. Small, nameless functions can be defined using the lambda keyword. This is a function that returns the sum of its two parameters: "lambda a, b: a+b”. The Lambda form can be used anywhere a function object is needed. Syntactically speaking, the lambda form is limited to one expression. Semantically, this is just a syntactic dessert for normal function definitions. Like nested function definitions, lambda forms cannot access variables in scopes that contain their definitions, but careful use of default parameters can bypass this limitation. For example:

def make_incrementor(n):
    return lambda x, incr=n: x+incr


4.7.5 Document string
Some conventions are being formed about the content and format of document strings. The first line should be a brief summary of the object purpose. For brevity, this line should not mention the name or type of the object, because these can be learned through other ways (of course, if the object name is a verb that describes the operation of a function, it can of course mention its name). The lines should start with larger letters and end with periods. If there are multiple lines in the document string, the second line should be empty lines, which separates the summary description from other descriptions. The following lines can be one or several paragraphs describing the call method of the object, its side effects, etc.

Python's scanner does not remove indentation blanks from multi-line strings, so the tools that handle documents need to handle indentation themselves. As long as the following conventions are followed, it can be beneficial to the processing of indenting blanks. The first non-blank line after the first line determines the indentation of the entire document string (we don't use the first line, because it is often followed directly by quotes indicating the beginning of the string). Each line in the document string except the first line must delete the blank space equivalent to the indentation amount of this line. The tab character will be expanded to spaces before deleting it.
Previous page12345678910Next pageRead the full text