Python path: Python functions

Source: Internet
Author: User

Functional programming: To encapsulate a function code into a function, you will not need to repeat the writing, just call the function

Object-oriented: classifying and encapsulating functions

Ii. definition and use of functions

def function name (parameter): ... function Body ...

The definition of a function has the following main points:

    • def: A keyword that represents a function
    • Function name: the names of functions, which are called later by function name
    • Function Body: A series of logical calculations in a function, such as sending a message, calculating the maximum number in [11,22,38,888,2], etc...
    • Parameters: Providing data for the function body
    • Return value: Once the function has finished executing, it can return data to the caller.

PS: More important parameters and return values

1. Return value

A function is a function block that executes successfully or is required to inform the caller by the return value.

def send text message (): Send SMS code ... if send success: Return Trueelse:return falsewhile true:# each time you execute the Send SMS function, the return value will be automatically assigned to result#, you can write the log according to result , or resend operation result = Send SMS () if result = = False: Record log, SMS send failed ...

2. Parameters:

Common parameters: Formal parameter, argument (parameter can have n, passed the number of parameters)

Default parameters: Do not pass in, use default values, default parameters must be placed at the end of the parameter list

Dynamic Parameters:

Accepts multiple parameters, automatically constructs tuples inside, and avoids internal building elements with *

Accept multiple arguments and pass in the dictionary with * *

Example: Sending an email

Import smtplibfrom email.mime.text import mimetextfrom email.utils Import formataddrmsg = mimetext (' message content ', ' plain ', ' utf- 8 ') msg[' from '] = FORMATADDR (["Lenliu", ' [e-mail protected] ') msg[' to '] = FORMATADDR (["Recipient", ' ******** @qq. com ']) msg[' Subject '] = "subject" Server = Smtplib. SMTP ("smtp.126.com") server.login ("[Email protected]", "email password") server.sendmail (' [email protected] ', [' ********@ Qq.com ',], msg.as_string ()) Server.quit ()

Map: Iterate through the sequence, manipulate each element in the sequence, and finally get a new sequence.

Li = [one, 33]SL = [1, 2, 3]new_list = map (lambda A, b:a + B, Li, SL)

Use the map () function to turn the non-canonical English text entered by the user into lowercase

Filter: Filters the elements in the sequence, and finally gets the sequence that matches the condition

Li = [one, one, 33]new_list = filter (lambda arg:arg > P, li)

Filter the sequence with the filter () function

V. Reduce: Cumulative operation for all elements in a sequence

Li = [one, three, 33]result = reduce (lambda arg1, Arg2:arg1 + Arg2, Li) # The first argument of reduce, the function must have two parameters # reduce the second parameter, to loop the sequence # reduce The third parameter, the initial value
Six, closure function: The function inside the closure cannot be called externally

Example 1:

Example 2:

Vii. Recursive functions: Internally invoking itself, this function is recursive function

Example 1: Recursive finding factorial

def fact (N): #定义函数

if n = = 1:

Return 1

Return N*fact (n-1)

Results:

>>>fact (5)

120

===> 5 * fact(4)===> 5 * (4 * fact(3))===> 5 * (4 * (3 * fact(2)))===> 5 * (4 * (3 * (2 * fact(1))))===> 5 * (4 * (3 * (2 * 1)))===> 5 * (4 * (3 * 2))===> 5 * (4 * 6)===> 5 * 24===> 120

Example 2:

def  fact_iter(product,count,max):
       if count>max:
            return product
         return fact_iter(product*count,count+1,max)
Results:
>>>fact_iter (1,1,5)
120
===> fact_iter(1, 1, 5)===> fact_iter(1, 2, 5)===> fact_iter(2, 3, 5)===> fact_iter(6, 4, 5)===> fact_iter(24, 5, 5)===> fact_iter(120, 6, 5)===> 120

Example 3:

def fact (N):
If n==1:
Return 1
Return N*fact (n-1)
Number=int (Input (' Please enter a positive integer: '))
Result=fact (number)
Print (the factorial of '%d is:%d '% (Number,result))

Example 4:

def func (ARG1,ARG2):
if arg1 = = 0:
Pass
Arg3 = Arg1+arg2
If Arg3 > 10:
Return ARG3
ret = func (ARG2,ARG3)
return ret

result = Func (0,5)
Print result

Python path: Python functions

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.