05-use of functions in python, 05-Use of python Functions

Source: Internet
Author: User

05-use of functions in python, 05-Use of python Functions

Function: modularize the program and encapsulate code blocks with independent functions as a whole into a function.

 

First print a Buddha to see:

Print ("_ ooOoo _") print ("o8888888o") print ("88. 88 ") print (" (|-_-|) ") print (" O \\=/O ") print ("____/'---'\\____") print (". '\\| | //'. ") print ("/\ |: | // \ ") print ("/_ | -: -|-\ ") print (" | |\\\\\-// | ") print ("| \ _ |'' \ ---/''|") print ("\\. -\\__'-'___/-. /") print ("___'.. '/--. --\\'.. _ ") print (". "" '<'. ___ \\_ <|> _/___. '> '"". ") print (" | :'-\ \'.; '\\_/';. '/-': | ") Print ("\\\\'-. \\___\\/___/. -'// ") print (" ====== '-. ____'-. ___\\_____/___. -'____. -'= ") print ("' = --- = '") print ("") print ("..................................... ........ ") print (" bugs in the bucket of Buddha ") print (" Buddha: ") print (" programmers in office buildings and office rooms ;") print ("programmers write programs, and get the program for money. ") Print. ") Print. ") Print? ")

In this case, if we want to print it many times, we cannot copy and paste it all the time. Therefore, we need to define a function for printing the Buddha:

Def print_fozhu (): # first define the function for printing Buddha. The function name is print_fozhu print ("_ ooOoo _") print ("o8888888o") print ("88. 88 ") print (" (|-_-|) ") print (" O \\=/O ") print ("____/'---'\\____") print (". '\\| | //'. ") print ("/\ |: | // \ ") print ("/_ | -: -|-\ ") print (" | |\\\\\-// | ") print ("| \ _ |'' \ ---/''|") print ("\\. -\\__'-'___/-. /") print ("___'.. '/--. --\\'.. __ ") Print (". "" '<'. ___ \\_ <|> _/___. '> '"". ") print (" | :'-\\'.; '\\_/';. '/-': | ") print ("\\\\'-. \\___\\/___/. -'// ") print (" ====== '-. ____'-. ___\\_____/___. -'____. -'= ") print ("' = --- = '") print ("") print ("..................................... ........ ") print (" bugs in the bucket of Buddha ") print (" Buddha: ") print (" programmers in office buildings and office rooms ;") print ("programmers write programs, and get the program for money. ") Print. ") Print. ") Print? ") Print_fozhu () # Call the print_fozhu function print_fozhu () below ()

Functions with Parameters

First, we define a function to calculate the sum of two numbers:

Def sum (): # defines a function, function Name: sum a = 20 B = 30 sum = a + B print ("% d + % d = % d" % (a, B, sum) sum () # Call this function below

Will this be a little too rigid? We hope we can input a and B on the keyboard to get the sum of the two numbers. What should we do?

Def sum (a, B): # define a function above. The function name is sum and contains two parameters a, B, the Parameter sum = a + B print ("% d + % d = % d" % (a, B, sum )) num1 = int (input ("1st values:") # The input value on the input Keyboard is of the string type. int () is required () convert to integer num2 = int (input ("2nd values:") sum (num1, num2) # When the sum function is called, it is equivalent to uploading num1 and num2 To sum () in the function, the parameter passed during the call is called the real parameter.

Root @ test :~ /Codes # python3 01-function with parameters-input. py
1st values: 10
2nd values: 50
10 + 50 = 60

Return: The result returned by the caller after a function in the program completes a task.

For example, I gave my friend 22 yuan and asked him to buy a pack of cigarettes for me. Then my friend bought it and handed it to me. This smoke is the return value.

This is also true when obtaining keyboard input:

In [1]: name = input ("Name:") Name: laowangIn [2]: nameOut [2]: 'laowang '# equivalent to obtaining a value from the keyboard, and the name

Here is an example to illustrate the function of return:

Def get_wendu (): # define a function get_wendu wendu = 22 # define a wendu variable print ("the current room temperature is % d" % wendu) def get_wendu_huashi (): # define a function to get the Fahrenheit temperature get_wendu_huashi wendu = wendu + 2 # assume that the Fahrenheit temperature = temperature + 2 print ("the current room temperature (Fahrenheit) is % d" % wendu) get_wendu_huashi () # Call the defined function, get_wendu_huashi

Let's take a look at the running results:
Traceback (most recent call last ):
File "02-Get temperature. py", line 10, in <module>
Get_wendu_huashi ()
File "02-Get temperature. py", line 7, in get_wendu_huashi
Wendu = wendu + 2
UnboundLocalError: local variable 'wendu' referenced before assignment # This statement indicates that the variable wendu has been called before it is declared, and the error is located.

Let me explain: the variables defined in the function can only be used in the current function and cannot be used in other functions, in addition, the function does not allow direct calls to the result. This means that the wendu variable defined in get_wendu does not recognize this wendu variable in get_wendu_huashi.

Let's take a look at the modified Code:

Def get_wendu (): wendu = 22 print ("current room temperature is % d" % wendu) return wendu # Here we use the return function, this means that we can return this value and the result to the calling place def get_wendu_huashi (wendu): # wendu is the form parameter, wendu = wendu + 2 print ("the current room temperature (Fahrenheit) is % d" % wendu) result = get_wendu () # A container is required to store the result during return, and then the result is stored in get_wendu_huashi (result) # When the get_wendu_huashi function is called, send the result variable as a real parameter to the function.

The running result is as follows:
Root @ test :~ /Codes # python3! $
Python3 02-Get temperature. py
The current room temperature is 22
The current room temperature (Fahrenheit) is 24

Success .....

Conclusion: if return exists in a function, it means that this function can return a value and a result to the called place. When return, there must be something to store the result, then, store the object during input.

 

If a function wants to have multiple return statements, you can write multiple return statements. However, once the function runs to return, the function ends, as shown below:

In [1]: def test (): # define a test function...: a = 11 # variable...: B = 22 # variable B...: return...: return B...: In [2]: a = test () # Call the test function and assign the result to aIn [3]: aOut [3]: 11In [4]: B = test () # Call the test function and assign the result to bIn [5]: bOut [5]: 11

So why is the value of a and B the same? Let's take a look at the process:

1. defined a test function

2. Define two variables a and B in the test function, and copy a = 11, B = 22 respectively.

3. return the value of a and the value of B using return.

4. Call the test function and assign it to.

5. Then start to enter the function, a = 11, B = 22, and return a. The result is assigned to a. At this time, a equals to 11, and the program ends.

6. in B = test (), enter the function, a = 11, B = 22, and return a. The result is assigned to B, and B is equal to 11, so the result of a and B is the same.

Why? Because in the function,Every time you call the functions function, you start from the beginning.You can write multiple return statements, but when you enter the function, the return program will end as soon as you see it, so the results of a and B are the same.

 

Modify the program as follows:

In [6]: def test():   ...:     a = 11   ...:     b = 22   ...:     return a,b   ...: In [7]: a,b = test()In [8]: print(a)11In [9]: print(b)22
Function Type

Functions can combine with each other based on whether there are any parameters or returned values.

(1) No parameter, no return value

(2) No parameters and return values

(3) There are parameters and no return values

(4) parameters and returned values

Nested Functions

When a function is called, another function is called. For example:

Def test1 (): passdef test2 (): print ("----- 2-1 -----") print ("----- 2-2 -----") def test3 (): print ("----- 3-1 -----") test2 () # Call the print ("----- 3-2 -----") test3 () # Call the test3 function in the function.

The program running result is as follows:
----- 3-1 -----
----- 2-1 -----
----- 2-2 -----
----- 3-2 ----
Def print_line (): # define a function and print 40 * print ("*" * 40) def print_5_lines (): # define a function, print 5 rows I = 0 while I <5: print_line () # sign in again and call the print_line function I + = 1print_5_lines ()

The program running result is as follows:
Root @ test :~ /Codes # python3 04-nested function call 2.py ***************************** **************************************** **************************************** **************************************** **************************************** **********

 

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.