Python function (1): initial function, python function initial

Source: Internet
Author: User

Python function (1): initial function, python function initial

After learning many basic python types, we can finally enter the next stage. Today we will enter a new world of functions.

Preview:

1. Write a function to calculate the numbers, letters, spaces, and other numbers in the input string. 2. Write a function, determines whether the length of the object (string, list, And tuples) imported by the user is greater than 5. 3. Write a function and check the length of the input list. If the length is greater than 2, only the content of the first two lengths is retained and the new content is returned to the caller. 4. Write a function to check and obtain all elements corresponding to the odd-digit index of the input list or tuples, and return the elements to the caller as a new list.
View Code

 

I. Function Definition

Function appearance

If we need to compare the two numbers, such as (), (), (15, 30), and so on, how can we write?

a,b = 4,5c,d = 10,20e,f = 15,30if a > b:    print(a)else:    print(b)if a > b:    print(a)else:    print(b)if a > b:    print(a)else:    print(b)
View Code

This piece of code shows to unprogrammed people that there are too many code and similar functions are basically repeated code.

This code has two problems:

1. Code Redundancy

2. Poor readability

At this time, we introduced our focus today-Functions

You just need to extract the duplicate code and put it in a public place and name it. Then, anyone who wants to use this code can call it through this name.

Def max_l (a, B): ''' is used to compare the size of two values: param a: the first number passed in: param B: The second number passed in: return: no return value ''' if a> B: print (a) else: print (B) max_l)
View Code

Definition:

The start of the def keyword, the space followed by the function name and parentheses (), and the last ":".

Def is fixed and cannot be changed. It must contain three consecutive letters and cannot be separated... They must be in love with each other.

In order to separate the def keyword from the function name, spaces must be blank. Of course, you can leave 2 or 3 spaces or leave 1 space normally.

Function Name:The function name can only contain strings, underscores, and numbers and cannot start with a number. Although the function name can be used at will, we should give the function name as short as possible and express the function.

Brackets:Required

Note:Each function should describe its functions and parameters accordingly. The first line under the function should be enclosed in multiple quotation marks. To enhance the readability of the Code.

Call:YesFunction Name ()Remember to add parentheses.

Summarize the benefits of using functions:

1. code reuse

2. Maintain consistency and ease of maintenance

3. scalability

 

Ii. return values of functions

Just now we have achieved a comparison and printed the results. But how can we use a variable to receive this value?

Return keyword

Return is a keyword. In pycharm, this word is translated as "return". Therefore, the value after return is called "return value"

To study the returned values, we also need to know that there are several situations in which the returned values are not returned, one value is returned, and multiple values are returned.

No return value

1. If no return is written, a first function written to None is returned by default, and no return is written. This is the case where no return value is returned.

2. Write only the return statement. If no other content is entered later, None is returned. Since no value is returned, you can leave the return statement completely. Why do you need to write a return statement? Because return has an important usage, that is, once return is encountered, the entire function is terminated.

3. return None

Returns a value.

We have just written a case where a value is returned. You only need to write the content to be returned after return.

Def max_l (a, B): ''' is used to compare the size of two values: param a: the first number passed in: param B: The second number passed in: return: no return value ''' if a> B: return a else: return ba = max_l () B = max_l () c = max_l () print (a, B, c)
View Code

Note: there must be a space between return and return values, and any data type value can be returned.

Returns multiple values.

Returns any number of data types.

Def ret_demo1 (): ''' multiple values are returned. '''return, 3, 4def ret_demo2 (): '''return multiple values of any type '''return 1, ['A', 'B'], 3, 4ret1 = ret_demo1 () print (ret1) ret2 = ret_demo2 () print (ret2)
View Code

Multiple returned values are organized into Meta groups and returned. You can also receive multiple values.

Def ret_demo2 (): return 1, ['A', 'B'], 3, 4 # return multiple values. Use one variable to receive ret2 = ret_demo2 () print (ret2) # Return multiple values. Multiple variables are used to receive a, B, c, d = ret_demo2 () print (a, B, c, d) # receive the returned values with multiple values: when several values are returned, they are received using several variables.
View Code

Summary:

Return Value = 0: Return None

Return Value = 1: return object

Return value> 1: tuple is returned.

 

Iii. Function Parameters

Just now, a function of the same size is a function with parameters. The example just returned is a function without parameters.

We will tell the max_l function who is going to calculate the string. This process is called passing a parameter (for short, passing a parameter, the "", "10, 20", "15, 30" we passed when calling the function, and the and B of the definition function areParameters.

Real participation Parameter

The "" "10, 20" "15, 30" we passed when calling the function is calledActual parameter,This is the actual content to be handed over to the function.Real parameters.

When defining a function, a and B are just the names of variables.Format parametersBecause it is only a form when defining a function, it indicates that there is a parameterParameters.

Multiple parameters are passed:Multiple parameters can be passed. Multiple parameters are separated by commas.

Location parameters

From the perspective of real parameters

1. Pass values by location

Def mymax (x, y): # at this time x = 10, y = 20 the_max = x if x> y else y return the_maxma = mymax () print (ma)
View Code

2. Pass values by keywords

Def mymax (x, y): # at this time x = 20, y = 10 print (x, y) the_max = x if x> y else y return the_maxma = mymax (y = 10, x = 20) print (ma)
View Code

3. Mixed Use of location and keyword forms

Def mymax (x, y): # at this time x = 10, y = 20 print (x, y) the_max = x if x> y else y return the_maxma = mymax (10, y = 20) print (ma)
View Code

Correct usage

The location parameter must be prior to the keyword Parameter

Only one parameter can be assigned once.

From the perspective of parameters

Location parameter value is required

Def mymax (x, y): # at this time x = 10, y = 20 print (x, y) the_max = x if x> y else y return the_max # Call mymax without passing the parameter ma = mymax () print (ma) # result TypeError: mymax () missing 2 required positional arguments: parameter 'X' and 'y' must be passed
View Code

Default parameters

1. Normal use

Why is there a default parameter: set the value with a small change to the default parameter

2. Definition of default parameters

Def stu_info (name, sex = "male"): "prints the student information function, because most of the students in the class are boys, therefore, set the default parameter sex to 'male' "print (name, sex) stu_info ('Alex ') stu_info ('eva', 'female ')
View Code

3. Parameter trap: the default parameter is a variable data type.

def defult_param(a,l = []):    l.append(a)    print(l)defult_param('alex')defult_param('egon')
View Code

Dynamic Parameters

Extra parameters for passing values by position are all received by * args and saved as a tuples.

def mysum(*args):    the_sum = 0    for i in args:        the_sum+=i    return the_sumthe_sum = mysum(1,2,3,4)print(the_sum)
View Code

Extra parameters for passing values by keyword are all received by * kwargs and saved as a dictionary.

def stu_info(**kwargs):    print(kwargs)    print(kwargs['name'],kwargs['sex'])stu_info(name = 'alex',sex = 'male')
View Code

 

Summary:

 

Preview answer:

Def length (str): ''' calculates the numbers, letters, spaces, and other numbers in the input string: param s: the user's access string: return: '''a = B = c = d = 0 for I in str: if I. isdigit (): a + = 1 elif I. isalpha (): B + = 1 elif I. isspace (): c + = 1 else: d + = 1 return a, B, c, dmsg = input ("please input:") a, B, c, d = length (msg) print ("number: {} letter: {} space: {} Other :{}". format (a, B, c, d) def length (str): ''' determines whether the length of the object (string, list, And tuples) imported by the user is greater than 5.: Param str: User-passed object: return Boolean value ''' if len (str) <= 5: return False else: return Truemsg = length ("hello world ") msg1 = length ([1, 2, 3, 4]) msg2 = length (1, 2, 3, 4, 5, 6) print (msg, msg1, msg2) def length (str ): ''' check the length of the input list. If it is greater than 2, only the content of the first two lengths is retained and the new content is returned to the caller.: Param str: Input list: return: returns the first two ''' if len (str)> 2: return str [0: 2] return strlist_l = [1, 2, 4, 4, 5, 6] print (length (list_l) def func (str): ''' check the elements corresponding to all odd-digit indexes of the input list or tuples, and return it to the caller as a new list.: Param str: Input list or tuples: return: new list ''' return str [1: 2] msg = (1, 2, 3, 4, 5, 6, 7, 8, 9) print (func (msg ))
View Code

 

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.