• In python, name of a function could be assigned to a variable, for example:
>>> a = abs;
>>> a(-12)
  • function definition:
def funtion_name(input_variable):
function body
return variables # usually *return* signifies the end of the function,
# without which function will return *None*. # Define a null function
def nop()
pass # *pass* could be used as a placeholder, to ensure a smooth running
  • import a self-defined function:
from name_of_function_definition_file (without .py) import function_name
  • two functions:

    1 isinstance: check type of parameter;

    2 raise TypeError('...'): return TypeError with '...' as additional information.
  • multiple returned values are actually one tuple;


  • Default parameters

    Note that defalut parameters must be unchangable objects.
# Set 'Westeros' and 'dead' as default parameters for 'loaction' and 'status' respectively
def game_of_thorn(name, gender, location = 'Westeros', status = 'dead'):
print('name: ', name)
print('gender: ', gender)
print('location: ', location)
print('status: ', status) >>> game_of_thorn('Eddard Satrk', 'M')
name: Eddard Stark
gender: M
location: Westeros
status: dead >>> game_of_thorn('Benjen Stark', 'M', 'the Wall')
name: Roose Bolton
gender: M
location: the North
status: dead # You could ignore the order of input parameters as long as you assign
# the inputs directly to certain parameters
>>> game_of_thorn('Cersei Lannister', 'F', status = 'alive')
name: Cersei Lannister
gender: F
location: Westeros
status: alive
  • Variable parameters
# An example
def calc(*numbers):
sum = 0
for n in numbers: # variable parameters are treated as a tuple
sum = sum + n * n
return sum >>> calc(1, 2)
5 >>> nums = [1, 2, 3]
>>> calc(*nums) # list or tuple inputs could be sent in as variables parameters as well
  • Keyword parameter

    Variable parameters are treated as a dict inside the function.
def person(name, age, **kw): # kw as keyword parameter
print('name:', name, 'age:', age, 'other:', kw) >>> person('Michael', 30)
name: Michael age: 30 other: {} >>> person('Adam', 45, gender='M', job='Engineer')
name: Adam age: 45 other: {'gender': 'M', 'job': 'Engineer'} >>> extra = {'city': 'Beijing', 'job': 'Engineer'}
>>> person('Jack', 24, **extra)
name: Jack age: 24 other: {'city': 'Beijing', 'job': 'Engineer'}
  • Named keyword parameter
def person(name, age, *, city, job): # Only those using 'city' and 'job' as
# keys will be accepted as keyword parameters
print(name, age, city, job) >>> person('Jack', 24, city='Beijing', job='Engineer')
Jack 24 Beijing Engineer # if there is alrealy a variable parameters in the function, then '*,'
# is not needed for named keyword parameters
def person(name, age, *args, city, job):
print(name, age, args, city, job)


1 for named keyword parameters, parameter name is always needed when using the function;

2 named keyword parameter could be assigned a default value;

3 all the parameters could be used in one time, while the input order should be: regular parameter, default parameter, variable parameter (*argus), named keyword parameter and keyword parameter(**kw).

# Any fuction could be called using func(*args, **kw)
def f1(a, b, c=0, *args, **kw):
print('a =', a, 'b =', b, 'c =', c, 'args =', args, 'kw =', kw) def f2(a, b, c=0, *, d, **kw):
print('a =', a, 'b =', b, 'c =', c, 'd =', d, 'kw =', kw) >>> args = (1, 2, 3, 4)
>>> kw = {'d': 99, 'x': '#'}
>>> f1(*args, **kw)
a = 1 b = 2 c = 3 args = (4,) kw = {'d': 99, 'x': '#'} >>> args = (1, 2, 3)
>>> kw = {'d': 88, 'x': '#'}
>>> f2(*args, **kw)
a = 1 b = 2 c = 3 d = 88 kw = {'x': '#'}

Recursive function

Recursive function is the one call itself. But a stack flow may appear with multiple recursion. One way to avoid the situation is : tail recursion.

A recursive function is tail recursive if the final result of the recursive call is the final result of the function itself ( Tail recursion occupies constant RAM, thus could effectively avoid stack overflow during function calling.

Meet Python: little notes 3 - function More articles about

  1. Meet python: little notes 4 - high-level characteristics

    Source: Slice Obtaining elements within required range from list or tu ...

  2. Meet Python: little notes 2

    From this blog I will turn to Markdown for original writing. Source: l ...

  3. Meet Python: little notes

    Source: Escape character: '\' - '\n': newline; - '\t': tab; - '\\': \; ...

  4. python 100day notes(2)

    python 100day notes(2) str str2 = 'abc123456' print(str1.endswith('!')) # True # Centers a string with the specified width and fills it with ...

  5. 70 It's a matter of attention Python Small Notes

    Python Reading notes :70 A little attention Notes author : Bai Ningchao 2018 year 7 month 9 Japan 10:58:18 Abstract : In the reading python In related books , Take a simple note of it . To pay attention to some details , Flexible use in future projects ...

  6. python A function of (function)

    # Let's learn about functions today ,function# When you define a function , Function will not be executed , Just call the function , Function to execute ## Defined function # # 1.def Is the key to create a function , Create a function # # 2. Function name # # 3.()# ...

  7. Python The core of programming ---- Function( function )

    Python edition :3.6.2   operating system :Windows   author :SmallWZQ As of the last essay <Python Data structure 4 ——set( aggregate )>,Python The basic knowledge is also introduced . Next, get ready to do ...

  8. [Python Study Notes] Anonymous functions

    Python Use lambda To create anonymous functions . lambda The name comes from LISP, and LISP It is from lambda calculus( A form of symbolic logic ) Take the name of . stay Python in ,lambda do ...

  9. [Python Study Notes] String processing techniques ( Continuous updating )

    ''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' ...

Random recommendation

  1. iOS Development of wechat chat toolbar encapsulation

    Before Shanzhai a Sina Weibo (iOS Summary of the Shanzhai version of sina Weibo ), Let's build a wechat these days . I have simply dragged the view structure of wechat before (IOS Wechat Shanzhai version of development ), Today, we will start to add specific functions to wechat , So let's start with wechat chat ...

  2. A trip through the Graphics Pipeline 2011_10_Geometry Shaders

    Welcome back.     Last time, we dove into bottom end of the pixel pipeline. This time, we’ll switch ...

  3. Android Insert pictures into the system album , There will be two in the album The same picture ( It's just that the size of the picture doesn't match )

    When this method is called to insert a picture into the system album , Two identical pictures will appear in the album MediaStore.Images.Media.insertImage One picture is the original, one picture is the thumbnail . In the form of :android4.4. ...

  4. The first 20 Chapter Use LNMP Architecture deployment dynamic website environment

    Chapter Overview : This section will start with Linux The software installation mode of the system , Lead readers to distinguish RPM The difference between software package and source code installation . And be able to understand their advantages and disadvantages . Nginx It's an excellent service program for deploying dynamic websites ,Nginx It has good stability ...

  5. turn :android in APK Start up and run automatically

    Background knowledge : When Android Startup time , It's going to send out a system broadcast , The content is ACTION_BOOT_COMPLETED, Its string constant is expressed as android.intent.action.BOOT_COMPLETED. only ...

  6. Extjs Store A detailed explanation of the use of The basic usage of Before use , First, create a Example , This is shown in the following code .       Every store You need at least two components to support , Namely proxy and reade ...

  7. springMVC Use jstl

    jsp Page to get data , The most convenient thing is to use jstl+EL 了 , All kinds of encapsulated functions are very easy to use , Next, write how to use jstl: 1. download jstl-1.2_1.jar 2. Because the project is : xmlns="ht ...

  8. nginx Jump to summary on the inside page of

      When I first joined the company, the boss always asked for php Do the inside page Jump , I didn't know the details at that time, so I didn't say anything . later php Ask me if you can jump inside , I said I would do a few , Since then, I have been working on internal page skipping for two weeks . As for why do inside page Jump which temporarily not ...

  9. 《 The finger of the sword Offer》 Question 51 ~ Question 60

    Fifty-one . Reverse pairs in arrays subject : Two numbers in an array , If the number in front is greater than the number in the back , Then these two numbers form a reverse order pair . Enter an array , Find the total number of reverse pairs in this array . for example , In the array {7, 5, 6, 4} in , A coexistence ...

  10. atitit. Hinduism and java The characteristics and concepts of religion attilax summary

    atitit. Hinduism and java The characteristics and concepts of religion  attilax summary 1. Java It's a religion 1 2. Java The doctrinal thought of , The concept of community , values 2 2.1.  Language of instruction , Similar to Hindu worship 2 ...