Full-stack python development-Day8 function basics, python-day8

Source: Internet
Author: User

Full-stack python development-Day8 function basics, python-day8
Full-stack python development-Day8 function basics I. Introduction

1. Why do we need to use functions instead of functions?

#1. The code's organizational structure is not clear and its readability is poor #2. When repeated functions are encountered, you can only write implementation code repeatedly. Code redundancy #3. When functions need to be extended, it is difficult to manage and maintain the function in a unified manner.

2. What is a function?

To solve the problem in No. 2 Middle School, imagine the example in life. The repairer needs to prepare tools such as hammers, wrenches, and pliers in the toolbox, and then use the hammers to solve the problem, instead of making a hammer temporarily. Repairer ==> a programmer has a certain function of a tool ==> to use a function, you must prepare it in advance and use it for reuse, need to be defined before using

3. Function Classification

#1. built-in functions for convenience of our development, for some simple functions, the python interpreter has already defined the built-in functions for us. For built-in functions, we can use them without prior definition, such as len (), sum (), max () ps: we will introduce the commonly used built-in functions in detail at the end. #2. udfs obviously have limited functions provided by built-in functions. Therefore, we need to customize our own functions to implement certain functions as needed. In the future, you can call a custom function in an application scenario.
Ii. define functions

1. How to customize functions?

# Syntax def function name (parameter 1, parameter 2, parameter 3,...): '''comment ''' value returned by return of function body # function name must reflect its meaning
1 def func (user, pwd): 2 ''' verify username and password ''' 3 if user = 'duoduo' and password = '000000 ': 4 5 return 1 # return 1 6 7 user = input ('user name >> :'). strip () 8 pwd = input ('password >> :'). strip () 9 res = func (user, pwd) 10 print (res) 11 12 # enter the correct user name and password. The value is 1.

2. Function usage principle: define and call

A function is a "variable". A "variable" must be defined first and then referenced. Directly referencing a function without definition is equivalent to referencing a nonexistent variable name # testing a def foo (): print ('from foo') bar () foo () # error: the function bar in the foo function is not defined yet. # Test 2. def bar (): print ('from bar') def foo (): print ('from foo') bar () foo () # normal # Test 3 def foo (): print ('from foo') bar () def bar (): print ('from bar') foo () # Will an error be reported? Yes! The function is undefined and cannot be called.
# Conclusion: to use a function, follow the principle: Define it first and call it later # when using a function, make sure that the region is defined and called.
# For more information, see http://www.cnblogs.com/manyqian/p/8137462.html#define the factorial def (): print ('from foo') bar () def bar (): print ('from bar ') # Call phase foo ()

A function is a "variable". A "variable" must be defined first and then referenced. Directly referencing a function without definition is equivalent to referencing a nonexistent variable name # testing a def foo (): print ('from foo') bar () foo () # Error # Test 2 def bar (): print ('from bar') def foo (): print ('from foo') bar () foo () # normal # Test 3 def foo (): print ('from foo') bar () def bar (): print ('from bar') foo () # Will an error be reported? # Conclusion: to use a function, follow the principle: Define it first and then call it # when using a function, make sure that the region is divided into definition stages and call stages # define stage def foo (): print ('from foo') bar () def bar (): print ('from bar') # Call phase foo ()

3. What do functions do in the definition phase?

# Only check the syntax. If you do not execute the code, the syntax errors will be detected in the function definition phase, and the logic errors of the Code will only be known during execution.

4. Define three forms of functions

#1. No parameters: only some operations are performed in the Application Scenario, such as interacting with users and printing #2. parameters: the logic can be executed only when parameters are passed in externally, for example, calculate the maximum length and minimum value. #3. Empty function: design the code structure.
# Definition phase def tell_tag (tag, n): # print (tag * n) def tell_msg (): # print ('Hello World') with no Parameter ') # Call phase tell_tag ('*', 12) tell_msg () tell_tag ('*', 12) ''' ************* hello world **************''' # conclusion: #1. No parameter is required during definition, which means that no parameter is required during the call. #2. parameters are required during definition.
Def auth (user, password): ''' auth function: param user: Username: param password: return: authentication result ''' pass def get (filename ): ''': param filename: return: ''' pass def put (filename): ''': param filename: return: ''' def ls (dirname ): ''': param dirname: return: ''' pass # architecture of the program
Iii. Call Functions

1. Call a function

Function call: function name brackets 1 first find name 2 call code by name

2. function return value

No return-> None # meaningless return None values are also Nonereturn 1 values-> return 1 value return multiple values separated by commas (,)-> tuples
When should I return a value? To call a function, after a series of operations and finally get a clear result, you must have a return value. Generally, a parameter function must have a return value. The input parameter is calculated, when do I need no return value to get the final result? To call a function, you only need to execute a series of operations. If you do not need any results, you do not need to return values. Generally, a function without parameters does not need to return values.

3. function call Methods

1 Statement Form: foo () 2 expression form: 3 * len ('hello') 3 another function parameter: range (len ('hello '))
Four function parameters

1. participate in real parameters

# The form parameter is the variable name, and the real parameter is the variable value. When a function is called, the value is bound to the variable name. After the function call is completed, the function is unbound.

2. Specific applications

#1. location parameters: parameters are defined in the order from left to right. location parameters: required. location parameters: parameters are passed by location. #2. Keyword parameters: real parameters defined in the form of key = value do not need to be passed according to the location of the parameter. Note: 1. the keyword real parameter must be on the right side of the position real parameter 2. values cannot be repeatedly transferred to the same parameter #3. default parameter: The parameter has been assigned a value when it is defined. values can be transferred or not transferred, it is often necessary to define a parameter as a location parameter. If a parameter with a small change is defined as a default parameter, note the following: 1. assign a value only once when defining 2. the default parameter must be defined on the right side of the positional parameter. default parameters should usually be defined as unchangeable types #4. Variable Length parameters: Variable Length refers to the number of real parameter values is not fixed, and real parameters are defined by location and by keyword, for the variable lengths of these two forms, the form parameter pairs should have two solutions to completely store them, namely * args, ** kwargs ========== * args ============ def foo (x, y, * args ): print (x, y) print (args) foo (1, 2, 3, 4, 5) def foo (x, y, * args): print (x, y) print (args) foo (, * [, 5]) def foo (x, y, z): print (x, y, z) foo (* [, 3]) =============** kwargs ========== def foo (x, y, ** kwargs ): print (x, y) print (kwargs) foo (1, y = 2, a = 1, B = 2, c = 3) def foo (x, y, ** kwargs): print (x, y) print (kwargs) foo (1, y = 2, ** {'A': 1, 'B': 2, 'C': 3}) def foo (x, y, z): print (x, y, z) foo (** {'Z': 1, 'x ': 2, 'y': 3 }) ============ * args + ** kwargs ============ def foo (x, y): print (x, y) def wrapper (* args, ** kwargs): print ('=>') foo (* args, ** kwargs) #5. Name keyword parameter: * The parameter defined later must be passed in values (except for those with default values), and must be passed in the form of real parameters of keywords to ensure that, the input parameter must contain some keywords def foo (x, y, * args, a = 1, B, ** kwargs): print (x, y) print (args) print (a) print (B) print (kwargs) foo (1, 2, 3, 4, 5, B = 3, c = 4, d = 5) Result: 1 x value 2 y value (3, 4, 5) args value 1 a value 3 B value {'C': 4, 'D': 5} kwargs Value

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.