Python notes--custom functions

Source: Internet
Author: User
Tags function definition


The function is to encapsulate the code of some payload, call it directly when needed, reuse it to improve efficiency and simplify the structure of the program.

1. Syntax

Define a function to use the DEF statement, write down the function name, parentheses, arguments in parentheses, colon :and then, in the indent block, write the function body, and the return value of the function is returned with a return statement.

def functionname (parms1, Parms2, ...): code block return expression

2. definition and invocation of functions


>>> def func1 (): print "AAA" return "BBB"

Note: When defining a function in a python interactive environment, the function definition will need to be returned to the >>> prompt by pressing two times.


>>> a=func1 () aaa>>> print abbb

Return function: Ends the statement block and returns a value. If there is no return statement or null followed by a return, the result is returned after the function is executed, except that the result is None.

In a Linux environment, where we define functions (such as func ()) in a . py file (such as, you can start the Python interpreter in the current directory of the file. Import the func () function with the FROM test-import func , and note that test is the file name (without the . py extension).

3. Null function

If you want to define an empty function that does nothing, you can use the PASS statement:

>>>def Func2 (): Pass

What's the use of a pass statement that doesn't do anything?

In fact, pass can be used as a placeholder, such as not yet how to write the code of the function, you can put a pass, so that the code can run. Pass can also be used in other statements, such as:

If Age >= 18:pass

Without the pass, the code will run with a syntax error.

4. function Parameters

>>> def func3 (name,age): #括号中的叫形参 print (Name,age) return (name,age) >>> a=func3 (' FJC ', #括号中的叫实参 (' FJC ', 25)


In general, a formal parameter can only have one argument, and when the function is called, if the number of arguments is incorrect, the Python interpreter automatically checks out and throws a TypeError error.

However, there are two types of parameters that can be used to correspond to multiple arguments, which are variable and keyword parameters, for example:

>>> def func4 (*name): #可变参数, there is a * print (name) >>> a=func4 (' Zhangsan ', ' Lisi ') (' Zhangsan '), ' Lisi ') #输出结果为一个元组 >>> def func5 (**dic): #关键字参数 with two x print (DIC) >>> A=func5 (zhangsan=12,l isi=15) #注意实参的格式 {' Lisi ': $, ' Zhangsan ': #输出结果为一个字典

Note: When the variable parameter and the keyword parameter appear in the same time, the variable parameter is in front, for example:

>>> def func6 (*AA,**BB): print AA print bb >>> func6 (1,2,3,a=1,b=2,c=3) (1, 2, 3) {' A ': 1, ' C ': 3, ' B ': 2

If you need to call a defined list or tuple or dictionary using a function, you need to add a * to the list or tuple before the dictionary with two *, for example:

>>> lis=[1,2,3]>>> dic={' a ': 1, ' B ':2}>>> a=[1,2,3]>>> b={' a ': 1, ' B ': 2, ' C ':3}> >> def func7 (*lis,**dic): Print (Lis,dic) >>> Func7 (*a,**b) #a前加一个 *,b before adding two * ((1, 2, 3), {' A ' : 1, ' C ': 3, ' B ': 2})


>>> def func8 (name,age=18): #注意: Default parameters can only be placed on the last print (name,age) >>> func8 (' Zhangsan ') of the formal parameter (' Zhangsa ') n ', 18)

#在调用函数时, arguments are not written sequentially, for example:

>>> Func8 (age=25,name= ' FJC ') #使用 "form parameter = argument" (' FJC ', 25)

5. Recursive Functions

Inside a function, you can call other functions. If a function calls itself internally, the function is a recursive function. For example:


>>> def func9 (n): If N==1:return n return n*func9 (n-1) >>> func9 (4) 24

The process of checking is as follows:

4*FUNC9 (3) ==>

4*3*FUNC9 (2) ==>

4*3*2*FUNC9 (1) ==>


The advantage of recursive functions is that they are simple in definition and clear in logic. In theory, all recursive functions can be written in a circular way, but the logic of the loop is not as clear as recursion.


1.Fibonacci Sequence (Fibonacci Sequence), also known as the Golden Section, refers to a sequence of such a series:0,1,1,2,3,5,8, -, +, the、......。

Enter two random numbers to generate a similar Fibonacci sequence.

#!/usr/bin/env pythondef func (*number): Lis=[first,second] for I in range: lis1=list (Reversed (LIS)) LEST=LIS1[0]+LIS1[1] Lis.append (lest) print (LIS) first=input ("Please input the first number:") second=input ("pl Ease input The second number: ") A=func (First,second)

#这个简单程序能够实现: Enter two numbers randomly in interactive mode, base the two numbers, and output the Fibonacci sequence.

3. Output 9*9 multiplication table

#!/usr/bin/env pythondef func (n,m): For x in Range (1,10): for y in range (1,x+1): print "%d*%d=%d\t"% ( X,y,x*y), print "" Func (1,10)


#!/usr/bin/env pythondef func (n,m):     For x in range (n,m):        for y in  Range (n,m):            if x>=y:      #设为x <=y, is another effect                  print "%d*%d=%d\t"% (x,y,x*y),             else:                 continue        print  "" A=func (1,10) 

1 , 2 , , 4 , how many three digits of a distinct and no repetition number can be formed? What's the number?

#!/usr/bin/env pythondef func (a,b,c,d):     f=0    for x in  (a,b,c,d):         for y in  (a,b,c,d):             for z in  (a,b,c,d):                 if x!=y and x!=z and z!=y:                     print  "%d %d%d "% (x, y, z)                      f+=1    print  "total:%d"%ffunc (1,2,3,4) 

6. Find the value of s=a+aa+aaa+aaaa+aa...a , where a is a number. For example 2+22+222+2222+22222 ( there are 5 numbers added at this time ), several numbers added by the keyboard control.

#!/usr/bin/env pythondef func (n,m): x=[] for I in range (1,m+1): x.append (int ("%d"%n*i)) print sum (x) n=in Put ("Number:") m=input ("Total:") func (N,m)

This article is from the "Network Technology" blog, please be sure to keep this source

Python notes--Custom functions

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: 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.