[Python] Function basic

Source: Internet
Author: User

Use the DEF Function name (): To define a function that is written as a indented block of the function body, returning the result as a return XX

For example:

def myabs (x):

If x >= 0:

return x

Else

Return–x

Variable parameters

Precede the parameter with an * number, the parameter received in the function is a tuple type, traversing

#可变参数

def mycalc (*nums):

Sum=0

For num in nums:

Sum+=num

return sum

Print (Mycalc ())

Iteration

Traversing a list or tuple through a for loop, which is called an iteration

Use for in to iterate over the List,for key in list: such as:

For item in MyList:

Print (item)

Use for in to iterate Dict,for k,v in D.items: such as:

user={"name": "Taoshihan", "Age": "100"}

For k,v in User.items ():

Print (k + "=" +v)

Slice

Take a list or tuple element, use the slice operator list[a:b], take the list of elements from A to B end (does not contain B)

Example: mylist=[1,2,3]

Print (Mylist[0:2]) output [1, 2]

function recursion

To find the factorial of n (n!)

def myfact (n):

If n==1:

Return 1

Return Myfact (n-1) *n

Print (Myfact (30))

Using tail recursion optimization to solve the stack overflow problem, the return statement cannot contain an expression, but the Python language does not introduce a tail recursion and therefore cannot be used

Solving the question of the Nottingham Tower:

def mymove (n,source,bridge,destination):

If n==1:

Print ("Move +" to "+destination" from "+source+")

Else

Mymove (N-1,source,destination, Bridge)

Print ("Move +" to "+destination" from "+source+")

Mymove (n-1,bridge,source,destination)

Mymove (5, "A", "B", "C")

Features of functional programming: Allows the function itself to be passed as a parameter to another function, and also allows the return of a function

[Python] Function basic

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.