Python Study Notes (5): Functions

Source: Internet
Author: User

We have seen some Python built-in functions, such as Len and rang. Now let's take a look at the custom function. The function is defined by the def keyword, followed by the function name and parentheses. The brackets can contain parameters. This row ends with a colon, followed by the statement block, that is, the function body.

1. Simple sayhello Function
 
Def sayhello (): Print ("Hello world! ") # Call the function sayhello ()
2. Functions with Parameters
 
Def printmax (A, B): If A> B: Print (a, "is maximum. ") else: Print (B," is maximum. ") printmax (3, 4)
3. Local Variables
 
Def func (x): Print ("X is", x) x = 2 print ("changed local X to", x) x = 50 func (X) print ("X is still", X)

The running result is:

X is 50
Changed local X to 2
X is still 50

4. default parameter values
 
Def say (message, Times = 1): Print (Message * times) Say ("ha") Say ("ha", 2)

The running result is:

Ha

Haha

5. Key Parameters
Def func (a, B = 5, c = 10): Print ("A is", a, "and B is", B, "and C is", c) func (3, 7) func (25, c = 24) func (C = 50, A = 100)

The running result is:

A is 3 and B is 7 and C is 10
A is 25 and B is 5 and C is 24
A is 100 and B is 5 and C is 50

6. Return Statement
 
Def maximum (x, y): If x> Y: Return x else: Return yprint (maximum (2, 3 ))
7. docstrings

Python has a wonderful feature: docstrings. Its main function is to help youProgramThe document is easier to understand.

 
Def printmax (x, y): ''' prints the maximum of two numbers. the two values must be integers. '''x = int (x) y = int (y) If x> Y: Print (x, "is maximum. ") else: Print (Y," is maximum. ") printmax (3, 5) print (printmax. _ Doc _) Help (printmax)

The running result is:

5 is maximum.
Prints the maximum of two numbers.
The two values must be integers.
Help on function printmax in module _ main __:

Printmax (x, y)
Prints the maximum of two numbers.
The two values must be integers.

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.