Python Automation Development Learning 3

Source: Internet
Author: User
Tags define local pow variable scope

Function

Through a function, you can define a block of code, which can then be called repeatedly by the function name

Define a function:

DEF alert (): "Print Hello World" print ("Hello World")

Using DEF to define a function, the second line suggests a function description using a document string.

Functions can be called repeatedly after using the function name.

Alert ()

return value of the function

At the end of the function, you can use return to define the return value, no retrun or return without an expression, and the return value is none. An example of a function above

DEF alert (): "Print Hello World" print ("Hello World") return # this line has the same as none, then you can remove the line and try a = alert () # Call the function and assign the return value to Apr Int (a) # to see if A is None

If there is a return value, the return value should be any type, and multiple values can be returned

def test1 (): Print ("This was Test1") return 0def test2 (): Print ("This is Test2") return 1, "Hello", ["Sunday", "Mo Nday "],{" name ":" Bob "}a = test1 () b = Test2 () print (a) print (b)

When multiple values are returned, they should also be handled by a value. The final result here is to put all the values in a tuple as the return value.

Summary of Return values:

    1. Return quantity = 0: Return None

    2. Return quantity = 1: Return object

    3. Return quantity >1: Return tuple

Parameters of the function

Define a function with parameters

def alert (msg): "Print msg, if it is string return 1, otherwise return 0" print (msg) return 1 if Type (msg) is str else 0a = alert (123) # when calling a function, you must also With the parameter print (a) # return is 0 because the number is not string b = Alert ("123") print (b) # return is 1, argument is string

Parameter : the variable allocates the memory unit only when it is called, and immediately releases the allocated memory unit at the end of the call. Therefore, the formal parameter is only valid inside the function. Function call ends when you return to the keynote function, you can no longer use the shape parametric

arguments: can be constants, variables, expressions, functions, and so on, regardless of the amount of the actual argument, they must have a definite value when making a function call to pass these values to the parameter. It is therefore necessary to use the assignment, input and other methods to get the parameters to determine the value

def power (x, y): "Computes the Y-side of X and returns" return (X**y) A, b = 3,2c = Power (A, B) print (c)

The X and Y in the above function are the formal parameters. And A and B, when the function is called later, are the arguments.

Key parameters

The parameters that are applied when calling the function above must correspond to one by one, and the number and position cannot be wrong. You can also use key parameters to refer to them.

def power (x, y): "Computes the Y-side of X and returns" return (X**y) A, b = 3,2c = Power (y=a,x=b) print (c)

This can also be mixed, but the key parameter must be behind the position parameter

def power (x, y): "Computes the Y-side of X and returns" return (X**y) A, b = 3,2c = Power (a,y=b) print (c)

The parameter A is the positional parameter, the value is passed to X, the remaining y=b is the key parameter, and the value of B is passed to Y.

Default parameters

See an example of a default parameter:

def introduce (name,age,country= "China"): Print (' My name is%s '%name) print ("I am%d years old"%age) print ("I am f Rom%s "%country" Introduce ("Jack", "introduce") ("Jack", "at", "Amarica")

If a function is defined with a pre-assigned value, the parameter has a default parameter. This default parameter can be omitted at the time of invocation, and if omitted, the default value is used, and the value of the call if there is a value

Other usage scenarios: Default installation path, default port number for connection service

Non-fixed parameters

When defining functions, you can use *args and **kwargs. This way, when the function is called, the extra participants pass in the 2 parameters.

def test1 (X,*args): # *args will turn multiple incoming parameters into a tuple print (X,args) test1 (1,2,3,4,5) test1 (1,*[2,3,4,5]) # You can also call Def test2 in this form (x,*a  Rgs,**kwargs): # **kwargs will turn multiple incoming key parameters into a dictionary print (X,args,kwargs) test2 (1,2,3,a=4,b=5) test2 (1,*[2,3],**{' a ': 4, ' B ': 5}) # can also be called in this form

It is possible to use any of the names of the variable naming conventions in the following theory, but it is recommended to use fixed names *args and **kwargs.

Local variables and global variables

A variable defined in a subroutine is called a local variable, and a variable defined in the program is called a global variable.

The global variable scope is the entire program, and the local variable scope is the subroutine that defines the variable.

When a global variable has the same name as a local variable: Local variables work within subroutines that define local variables, and global variables work in other places.

Name = "Alice" # first defines 2 global variables age = 23def test1 (): Print (name,age) # 2 variables here or global variables Def test2 (): name = "Jerry" # here defines Local variable name, does not affect the global variable print (name,age) # Here's name is local variable, age or global variable test1 () test2 () print (name,age) # Here the value of the 2 global variables does not change

Therefore, you can use both global variables and your own local variables in subroutines. If the global variable and local variable have the same name, changing the local variable does not affect the global variable.

But if you want to change global variables in a subroutine, you can declare it through global.

Name = "Alice" # first defines 2 global variables age = 23def test2 (): Global name # declares that name is a globals variable name = "Jerry" # This changes the value of name to see if the global variable has changed Print (name,age) printing (name,age) # prints 2 global Variables test2 () # Call a function that modifies the Nameprint (name,age) # The global variables here are also modified

Method can be implemented, but try not to use it, do not change global variables in subroutines, let's not define global variables.

Finally look at the list in the subroutine, the list, the dictionary, the collection of such data types have no local variables.

name = [' Alice ', ' Bob ', ' Carl '] # define global Variables Def test (): Print (name[1]) name[1] = "Jack" # Modify an element of an array print (name) # Print first number of times Group Test () # Call function, change an element in the array print (name) # Although the function does not use global, the elements in the array are changed.

Recursive

Inside a function, you can call other functions. If a function calls itself, then the function is a recursive function.

Characteristics of recursion:

    1. Must have a definite end condition

    2. Each time you enter a deeper level of recursion, the problem size should be reduced compared to the last recursion

    3. Recursive efficiency is not high, too many recursive levels will cause stack overflow. (Python is recursive up to 999 layers and will be error-aware)

Examples of recursion:

def halve (n): "Halve each time and turn to shaping until 0" print (n) n = int (N/2) if n > 0:halve (N) halve (100)

Higher order functions

A variable can point to a function, and the parameter of the function receives the variable. In addition, a function can receive another function as a parameter, which is called the higher order function. To illustrate:

def fxy (x,y,f): "Returns the value of X and Y after the F function is processed" return f (x, y) A = Fxy (3,6,min) # min is a built-in function, the minimum value B = Fxy (3,6,max) # Max is a built-in function that asks for the maximum value C = Fxy (3,6,POW) # POW is a built-in function, exponentiation. 3 of the 6-time Square is 729print (a,b,c)

Homework

Payroll Management System

Alex 100000

Rain 80000

Egon 50000

Yuan 30000

-----above are info.txt file-----

Implementation results:

Read employees and their payroll information from the Info.txt file, and finally write the revised or increased employee payroll information to the original Info.txt file.

Effect Demo:

1. Check the employee's salary

2. Revise employee's salary

3. Add new Employee Records

4. Exit

>>:1

Please enter the name of the employee to be queried (ex: Alex): Alex

Alex's salary is: 100000.

1. Check the employee's salary

2. Revise employee's salary

3. Add new Employee Records

4. Exit

>>:2

Please enter the employee name and salary to be modified, separated by a space (for example: Alex): Alex 10

Modified successfully!

1. Check the employee's salary

2. Revise employee's salary

3. Add new Employee Records

4. Exit

>>:3

Please enter the employee's name and salary to be added, split the total space (ex: Eric 100000): Eric 100000

Increase success!

1. Check the employee's salary

2. Revise employee's salary

3. Add new Employee Records

4. Exit

>>:4

Good bye!


Python Automation Development Learning 3

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.