Python guide: Control Structures and functions

Source: Internet
Author: User
Tags assert exception handling finally block variable scope in python

1, control structure 1.1 piece branch 1.2 circulation 1.2.1 while loop 1.2.2 for loop 2, exception handling 2.1 Catch Exception 2.2 Produce exception 2.3 Custom exception 3, custom function 3.1 name and Docstrings 3.2 parameter and parameter split 3.3 Accessing the global scope variable 3.4 lambda function 3.5 assertion

1. Control Structure

Python implements the branch through the IF statement, loops through the while statement and the for...in statement, and a conditional expression (similar to the C-language three-mesh operator) that is implemented through the IF. 1.1 pieces of branch

The most common syntax for Python conditional branching statements is as follows:

If Boolean_expression1:
    suite1
elif boolean_expression2:
    suite2
...
Elif boolean_expressionn:
    suiteN
Else:
    

You can have 0 or more elif statements, and the last else statement is optional. If you do not want to do anything in a branch , you can use pass as the suite for that branch.

To implement the three-mesh operator with a conditional branch:

expression1 If boolean_expression else expression2

If Boolean_expression is true, the conditional expression is expression1, otherwise expression2. As an example:

x = (1 if True else 0)
print (x)

[out]
1

Note the use of parentheses, if you do not use parentheses, we may fall into some traps, look at the following two code differences:

x = ten + 5 if False else 0
print (' A: ', x)

x = ten + (5 if False else 0)
print (' Secont: ', x)

[out]
F irst:0
Secont:10

As you can see from the results, if you don't use parentheses, Python sees "10+5" as the expression1 part of the conditional expression. 1.2 Cycle

Python provides two ways to loop: while and for...in. 1.2.1 While loop

Syntax format:

While Boolean_expression:
    while_suit
Else:
    else_suit

The Else branch is optional. If the boolean_expression is true,while_suite, it is executed, otherwise the loop terminates. If the continue statement is executed inside the while_suite, it jumps to the beginning of the loop and evaluates the Boolean_expression value.

If an else branch exists, the Else_suite executes if the loop is terminated normally. Else_suite does not execute if the loop is thrown out because of a break statement, a return statement, or a result of an exception.

Let's take a look at the actual use of the Else branch. Str.index () and List.index () return the position of the given string or data where it is to be indexed, resulting in a valueerror exception if it is not found. Now let's change the policy: If the data item is not found, return-1.

# While...else ... Instance
def list_index (LST, target):
    index = 0 while
    index < Len (LST):
        if lst[index] = = target:
            break< C5/>else:
            index + 1
    else:
        index =-1 return
    index

# test
lst = [1, 2, ' cat ', ' apple ']
print (' Index of ' apple ': ', List_index (LST, ' Apple ')]
Print (' Index of 9: ', List_index (LST, 9))

[out]
index of "Apple": 3
Index of 9:-1

From the output, we know that the effect we want has been achieved. 1.2.2 For Loop

Syntax format:

For expression in iterable:
    for_suit
Else:
    else_suit

The Else branch is optional. If the continue statement is executed within the For_suite, the control flow immediately jumps to the beginning of the loop and begins the next iteration.

The following List_index () is implemented using for...in loops:

# for...in version
def list_index2 (LST, target):
    for index, value in enumerate (LST):
        if value = = target: Break
    Else:
        index =-1 return
    index

# test
lst = [1, 2, ' cat ', ' apple ']
print (' Index of ' apple ': ', list_i Ndex (LST, ' Apple ')]
print (' Index of 9: ', List_index (LST, 9))

[out]
index of "Apple": 3
Index of 9:-1
2. Exception Handling

Python indicates that an error or exception condition has occurred by generating an exception. 2.1 Catching Exceptions

The catch of an exception is implemented using a try...except block, and its syntax is as follows:

Try:
    try_suite
except Exception_group1 as variable1:
    except_suite1
...
Except EXCEPTION_GROUPN as Variableb:
    except_suiten
Else:
    else_suite
finally:
    finally_ Suite

At least one except block must be included, else and finally blocks are optional. After the normal execution of the try_suite is performed, the else_suite--will not execute if an exception occurs. If a finally block exists, it is always executed at the end.

The as variable for each except branch is optional and, if used, the variable contains the exception that occurred and can be accessed in the suite of exception blocks.

To match an exception group, the exception must be consistent with the type of exception listed in the group (or one of them), or a subclass of the exception type (or one of them) listed in the group, listing the partial screenshot of the Python exception system:

We use exceptions to implement the previous List_index () function:

# abnormal version
def list_index3 (LST, target):
    try:
        index = lst.index (target)
    except ValueError:
        index = -1< C6/>return Index

# test
lst = [1, 2, ' cat ', ' apple ']
print (' Index of ' apple ': ', List_index (LST, ' apple '))
Print (' Index of 9: ', List_index (LST, 9))

[out]
index of "Apple": 3
Index of 9:-1

A common application of try...except...finally block is to handle file errors, we open the file to produce an exception, the processing process is abnormal or normal processing is complete, anyway we need to close the file, finally can help us always close the file. 2.2 Generates an exception

We can create our own exceptions to produce the exceptions we need and process them. The syntax that produces the exception is as follows:

Raise Exception (args)

Raise exception (args) from original_exception

Raise

Using the first syntax, the specified exception should be a built-in exception or a custom exception that inherits from exception. If some text is given as a parameter to the exception, the text should be output information when the exception is caught and printed.

With the second syntax, where no exception is specified, raise will recreate the currently active exception, and if not, a typeerrorwill be generated. 2.3 Custom Exceptions

Custom data type (class) when customizing the exception. The syntax for creating custom exceptions is as follows:

Class Exceptionname (baseexception):p

Its base class should be a exception class or a class that inherits from exception.

One use of custom exceptions is to jump out of a deep nested loop .

Here's a simple custom exception example:

# Custom Exception
class Myerror (Exception):
    def __init__ (self, value):
        self.value = value
    def __str__ (self): Return
        repr (self.value)

try:
    raise myerror except
Myerror as E:
    print (' There is a myerror, Value: ', E.value)

[out]
There is a myerror, value:10
3. Custom Function

Functions can be used to package and parameterize related functions. In Python, you can create 4 functions: global Functions , Local functions ,lambda functions , methods . A global function can be accessed by any code in the same module (the same. py file) that created the function. Local functions (also called nested functions ) are defined within other functions and are visible only to functions that are defined on them. A lambda function is an expression, so you can create it where you want to use it. Methods are functions that are associated with a particular data type and can only be associated with a data type.

The parameters of the function can specify default values, such as Def add (A, b=1). Note that the default values, such as Def Bad (A, b=1, c), are not allowed following parameters that do not have a default value. 3.1 names and docstrings

For the name of a function or variable, there are some lessons to consider: using uppercase for constants, using Titlecase for classes (including exceptions), using Camel-case for GUI functions and methods, using lowercase or lowercase_ for other objects With_underscores. For all names, avoid using abbreviations. The function name and method name should be able to indicate its behavior or return value.

We can add Document information to any function, docstring can simply add a string after the Def line, before the function code starts. Here's an example of a function in the requests Library:

def get (URLs, Params=none, **kwargs):
    R "" "sends a GET request.

    :p Aram Url:url for the New:class: ' Request ' object.
    :p Aram params: (optional) Dictionary or bytes to is sent in the query string for the:class: ' Request '.
    :p Aram \*\ *kwargs:optional arguments that "request" takes.: Return
    :: Class: ' Response <Response> ' object
    : Rtype: Requests. Response
    "" "

    kwargs.setdefault (' allow_redirects ', True) return
    request (' Get ', URL, params=params, * * Kwargs)

In the case of a function document, if it is longer than the function itself, it is not unusual, as the general practice is, DocString's first line of knowledge is a short description, followed by a blank line, followed by a complete description of the information, if the interactive input to execute the program, but also give some examples. 3.2 parameter and parameter splitting

As discussed in the previous section, we can use the sequence split operator (*) to provide positional parameters. We can also use the sequence splitter operator in the function argument list, which is valid when creating a function that uses a variable number of positional parameters.

# parameter Split
def product (*args):
    print (Type (args))
    print (args)

product (1, ' Love ', 2) [out

]
<class ' tuple ' >
(1, ' Love ', 2)

It can be seen from the output that the type of the parameter args within the function is a tuple, and the number of items varies with the number of positional parameters given.

We can follow the keyword parameter after the position parameter, for example:

# keyword parameter followed by position parameter
def sum_of_powers (*args, power=1): Result
    = 0 for
    arg in args: result
        = arg * *
    Power return result


print (Sum_of_powers (1, 3, 5))
print (Sum_of_powers (1, 3, 5, power=2))

[out]
9
35

It is also possible to use the * itself as a parameter to indicate that a positional parameter should not appear after the *, but that the keyword parameter is allowed.

# * passed through
def Heron (A, B, C, *, units= ' meters '):
    s = (A + B + C)/2 return
    ' {} {} '. Format (s, units)


print (Heron (in))
Print (heron, units= ' inches '))
print (Heron (in,, ' inches '))

[out]
31.0 meters
31.0 inches
Traceback (most recent call last):
  File "D:\Programming\Python\ fourth chapter control structure and function. py", line $, in <mo dule>
    Print (heron, ' inches ')
Typeerror:heron () takes 3 positional arguments but 4 were given

Just as we can split a sequence to produce a function's positional parameters, we can also use the mapping split operator (* *) to split the mapping.

# parameter sequence split
def print_dict (key= ' Defkey ', value= ' defvalue '):
    string = ' key = {}, value = {} '. Format (key, value)
    R Eturn string


options = dict (key= ' Hello ', value= ' world ')
print (Print_dict (**options))

[out]
key = Hello, value = World
3.3 Accessing variables of global scope

We often set some global constants in the program, which is reasonable and sometimes defines some global variables, although this is not good practice. To read or modify a global variable in a function, you need to add the global keyword before, for example:

# access to global variables price
= 8.9


def raise_price ():
    Global price
    print (' The original Price is: ${}. '. Format (price) Price
    + + 1
    print (' The lastest Price is: ${}. '. Format (price)


raise_price () [out] The original price is
: $8.9. 

The role of global is higher vocational python,price variable scope is global, the assignment of variables should be applied to global variables, rather than creating a local variable with the same name. If you do not use the global statement, the program can run, but Python looks in the local (function) scope and creates a new local variable named price without changing the global price variable. 3.4 lambda function

Syntax format for lambda functions:

Lambda parameters:expression

Parameters is optional and, if provided, is usually a comma-delimited form of variable names, i.e. positional arguments. Expression cannot contain branches or loops, nor can you include a return (or yeild) statement, and the result of a lambda expression is an anonymous function . Anonymity is no longer defining a function in a standard form such as a DEF statement.

We know that the bottom of the triangle is B, and the height is H, and before we write a function that asks for an area to write like this:

def area (b, h): return
    0.5 * b * H

So how do you write with anonymous functions?

Area = Lambda b,h:0.5 * b * H

The anonymous function does not need a return value, and the result of the expression itself is the return value.

Advantages of anonymous functions: using a lambda to write some scripts, you can omit the process of defining a function and make your code more streamlined. For some abstract functions that will not be reused elsewhere, sometimes the name of a function is also a problem, and using a lambda does not need to be considered a naming problem. Using a lambda at some point then the code is easier to understand 3.5 assertions

To avoid the effect of invalid data on the program, we can declare the premises and consequences, which can be implemented using an assert statement, with the syntax in the following format:

Assert Boolean_expression, Optional_expression

If Boolean_expression evaluates to False , a assertionerror exception is generated. If an optional optional_expression is given, it is used as a parameter to the Assertionerror exception.

Note: assertions are designed for developers, not for end-users .

There is a product function that requires all parameters to be non-0 values and treats the call using parameter 0 as a coding error, with two versions of equivalence below:

# Assert statement, version 1
def product1 (*args):
    assert All (args), ' 0 argument ' result
    = 1 for
    arg in args:
        Result *= Arg return result


# version 2
def product2 (*args): Result
    = 1 for arg in
    args: result
        *= Arg
    assert result, ' 0 argument ' return result
    

Version 1 checks all parameters for each call, and version 2 checks the results only. If a parameter is 0, a assertionerror is generated and an error message is written to the error stream (usually the console):

x = Product1 (0, 1, 2, 3, 4)

[out]
traceback (most recent called last):
  File "D:\xxx\ fourth chapter control structure and function. py", line 160, I n <module>
    x = Product1 (0, 1, 2, 3, 4)
  File "D:\xxx\ fourth chapter control structure and function. py", line 144, in Product1
    assert all (AR GS), ' 0 argument '
assertionerror:0 argument

Manually removing ASSERT statements when the program is ready to be published is inefficient, and we can tell Python not to execute ASSERT statements: When running a program, specify the- o option on the command line. Another way is to set the environment variable pythonoptimize to O .

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.