[Python] basic functions, python Functions

Source: Internet
Author: User

[Python] basic functions, python Functions

Use def function name (): to define a function. The function body is written in the form of an indention block. The returned result is return xx.

For example:

Def myAbs (x ):

If x> = 0:

Return x

Else:

Return-x

Variable parameters

Add a * sign before the parameter. The parameter received in the function is of the tuple type. traverse it.

# Variable parameters

Def myCalc (* nums ):

Sum = 0

For num in nums:

Sum + = num

Return sum

Print (myCalc (1, 2, 3 ))

 

Iteration

List or tuple traversal through a for loop is called iteration.

Use for in to iterate the list, for key in list:, for example:

For item in myList:

Print (item)

Use for in to iterate dict, for k, v in d. items:, for example:

User = {"name": "taoshihan", "age": "100 "}

For k, v in user. items ():

Print (k + "=>" + v)

 

Slice

 

Take some elements of a list or tuple and use the slice operator list [a: B]. The elements of the list start from a to B (excluding B)

Example: myList = [1, 2, 3]

Print (myList [0: 2]) Output [1, 2]

 

 

 

Function Recursion

Returns the factorial (n!) of n !)

Def myFact (n ):

If n = 1:

Return 1

Return myFact (n-1) * n

 

Print (myFact (30 ))

Tail recursion optimization is used to solve the stack overflow problem. The return statement cannot contain expressions, but the Python language does not introduce tail recursion. Therefore, it cannot be used.

Solve the following problems:

Def myMove (n, source, bridge, destination ):

If n = 1:

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

Else:

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

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

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

 

MyMove (5, "a", "B", "c ")

 

Function programming features: allows the function itself to be passed into another function as a parameter, and allows the return of a function

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.