python exception handling and function introduction

Keywords: Lambda Python

One anomaly

1 Concept: An exception is an event that occurs during the execution of a program, affecting the normal execution of the program. Typically, an exception occurs when Python cannot properly handle the program.
An exception is a Python object that represents an error. When an exception occurs to a Python script, we need to capture and process it, otherwise the program will terminate execution.
Writing: try:... .except
If there are errors, the code will enter the specified except according to the type of error. The advantage of this is that the code does not interrupt execution because of errors.

list = [1, 2, 3, 4, 5]
dic = {}
try:
    print('--------')     # Judging whether try is executed
    print(list[14])
    print(dic['age'])
except IndexError as e:
     print('An index error was caught{}'.format(e))
     # An index error list index out of range was captured
except KeyError as e:
     print('A keyword error was caught{}'.format(e))

Of course, it can also be abbreviated as:

try:
    print(list[21])
# Exception and IndexError,KeyError as the relationship between father and son
except Exception as e:
    print('An error was caught{}'.format(e))
    # Output: Captured an error list index out of range

3 try.else and finally:

try:
     pass
 except:
     pass
 else:
     pass
 finally:        
     pass

If there are no errors, execute the else module, but finally will absolutely execute
4 Manual throw exception

age = input('Please export your age')
age = int(age)
if age < 0:
    print('Age is not right.')
    raise Exception('Age is not right. Be sure to enter a value greater than 0.')

Two function

  1. Definition: Functions are organized, reusable code segments for single, or related functions. Written as follows:
The function code block begins with the def keyword, followed by the function identifier name and parentheses ().
Any incoming parameters and independent variables must be placed in the middle of parentheses. The parentheses can be used to define parameters.
The first line statement of a function can optionally use a document string -- to store function descriptions.
Function content starts with a colon and is indented.
return [expression] ends the function, selectively returning a value to the caller. return without expression is equivalent to
  1. Function parameters:
    When declaring a method, if there are parameters, then the calling method must have parameters. The parameters used to declare a method are called parameters (parameters are variables), and the parameters used to invoke a method are called arguments (parameters are assigned to variables).
    Parameters are divided into: essential parameters, keyword parameters, default parameters, variable length parameters.
    (1) Required parameters: Functions must be passed in the correct order, and the number of calls must be the same as when they are declared.
def fun1(name,age):
    result = 'My name is{}'.format(name,age)
    return result
print(fun1('Zhang San',18))

(2) Keyword parameters
Functions use keyword parameters to determine the values of incoming parameters, and keyword parameters allow the order of parameters when a function is called to be different from when it is declared, because the python interpreter can match parameter values with parameter names.

def fun1( name, age ):
   "Print any incoming string"
   print ("Name: ", name)
   print ("Age ", age)
   return
 fun1( age=50, name="miki" )
 //Output:
 Name:  miki
Age  50

(3) Default parameters
When calling a function, if the default function value is not passed in, it is considered as the default value. Note that the default parameter must be placed at the end of the parameter value, and the order can not be disorderly.

def fun2( name, age = 35 ):
   "Print any incoming string"
   print ("Name: ", name)
   print ("Age ", age)
   return
fun2( age=50, name="miki" )
fun2( name="miki" )
//Output:
Name:  miki
Age  50
Name:  miki
Age  35

(4) Uncertain length parameter
Sometimes a function may be needed to handle more parameters than was originally declared. These parameters are called indefinite length parameters and are used as follows
def fun(*args,**kwargs): Put the extra parameters in it.

def fun1(a,b,*args):
    print('a The value is{}'.format(a))
    print('b The value is{}'.format(b))
    print('args The value is{}'.format(args))
    print('{} + {} = {}'.format(a,b,a+b))
fun1(10,15)
fun1(10,15,20,30)
//Output: a has a value of10
b The value is15
args The value is()
10 + 15 = 25

a The value is10
b The value is15
args The value is(20, 30)
10 + 15 = 25

Here's the question of * args and ** kwargs afferent parameters

def fun1(a, *args, **kwargs):
    print('a The value is{}'.format(a))
    print('args The value is{}'.format(args))
    print('kwargs The value is{}'.format(kwargs))


fun1('Hello')
fun1('nice', 'to', 'meet', 'you')
//Output:
a The value is nice
args The value is('to', 'meet', 'you')
kwargs The value is{}
#name and age are not key parameters

fun1('hello', name='Zhang San', age=19)
//Output:
a The value is hello
args The value is()
kwargs The value is{'name': 'Zhang San', 'age': 19}

fun1(20, [{'name': 'Zhang San'}])
 //Output:
a The value is20
args The value is([{'name': 'Zhang San'}],)
kwargs The value is{}

3 Global and local variables
All variables of a program are not accessible anywhere. Access rights depend on where the variable is assigned.
Generally speaking, variables defined within a function have a local scope, while variables defined outside a function have a global scope. Local variables can only be used inside the functions they define, while global variables can be used anywhere in the functions.

name = 'Zhang San'
def fun1():
    print(name)
    name = 'Li Si'
    print(name)
    # UnboundLocalError: local variable 'name' referenced before assignment
fun1()
name = 'Zhang San'
def fun1():
    name = 'Li Si'   # What's different from the above is to declare before using it.
    print(name)
fun1()

Pay attention to the details of the above usage.

name ='Zhang San'
def fun1():
    global name     
    print(name)
    name ='Li Si'
    print(name)
fun1()
Output:
Zhang San
 Li Si

The function of the return statement is to use the results inside the method for external use.
Advanced usage of 5 functions:
(1) Anonymous functions:
python uses lambda to create anonymous functions. lambda is just an expression with its own namespace and can't access parameters outside its own parameter list or in the global namespace.
Usage: lambda [arg1 [,arg2,... ... argn]:expression

result = lambda x, y: x + y   
print(result(5, 6))  
//Output:11

Usage:

list1 = [1, 11, 56, 24, 99, 65, 46]
list2 = sorted(list1, key=lambda x: x)    # x: Represents traversal
print(list2)
//Output:1, 11, 24, 46, 56, 65]
list3 = [
    {
        'name': 'Zhang San',
        'age': 16
    },
    {
        'name': 'Li Si',
        'age': 17
    },
    {
        'name': 'Wang Wu',
        'age': 13
    }
]

list3 = sorted(list3, key=lambda x: x['age'])  # X denotes traversal x['age']
print(list3)
//Output: ['name': 'Wang Wu', 'age': 13}, {'name': 'Zhang San', 'age': 16}, {'name': 'Li Si', 'age': 17}]
list4 = sorted(list3, key=lambda x: x['age'], reverse=True)
print(list4)
//Output: ['name': 'Li Si', 'age': 17}, {'name': 'Zhang San', 'age': 16}, {'name': 'Wang Wu', 'age': 13}]

The key=lambda x:x ['age'] above indicates sorting by age size

list5 = [
    {
        'name': 'Zhang San',
        'info': {
            'age': 14,
            'height': 165
        }
    },
    {
        'name': 'Li Si',
        'info': {
            'age': 19,
            'height': 168
        }
    },
    {
        'name': 'Wang Wu',
        'info': {
            'age': 17,
            'height': 173
        }
    }
]

list5 = sorted(list5, key=lambda x: x['info']['age'])
print(list5)

list6 = sorted(list5, key=lambda x: x['info']['height'])
print(list6)

6 eval(): Execute the contents in parentheses as code

result = '12 / 3 * 4'
content = eval(result)
print(content) 
//Output:16.0

(Use cautiously to ensure safety)
7 map usage
Map accepts two parameters. The first parameter is a function and the second parameter is a sequence. The meaning of map function is to process each value in the sequence in the previous function and return a new list.
map and lambda square:

result = list(map(lambda x: x**2, [1,2,3]))
print(result)

Look up the keywords in the dictionary

def my_map(string):
    all_number_list = {
        '0':' zero '.
        '1':' one ',
        '2':' two ',
        '3':' three ',
        '4':' four ',
        '5':' five '.
    }
    return all_number_list[string]
    # This is a dictionary. The way to find values by keys is dict['key'] as above.
result = list(map(my_map, '54321'))
Find the corresponding values of 5,4,3,2,1 respectively.
That is to say, five, four, three, two and one are put into my_map() function and processed in turn, and the results are put in the list.
print(result)
Output: ['5','4','3','2','1']

8 reduce usage
The reduce() function accepts the same parameter map() function, except that the reduce() function calls the function repeatedly for each element in the sequence and returns a final result.
Python 3 cancels the reduce() built-in function, which is referenced by import reduce from functools before use.

def my_reduce(x, y):
    return x + y
print(reduce(my_reduce, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]))
Here is 1 + 2 = 3, 3 + 3 = 6, and 6 + 4 = 10.

Posted by bladecatcher on Wed, 15 May 2019 05:48:30 -0700