python entry-five (function) [5-4 python defined variable Parameters

5-4 python defined variable parameter

The variable parameters defined Python

If you want a function can accept any number of parameters, we can define a variable parameter:

1 def fn(*args):
2     print args

In front of the name of the variable parameters have a asterisk, we can pass in 0, one or more parameters to the variable parameters:

>>> fn()
()
>>> fn('a')
('a',)
>>> fn('a', 'b')
('a', 'b')
>>> fn('a', 'b', 'c')
('a', 'b', 'c')

Variable parameter is not very mysterious, Python interpreter will assemble a set of parameters passed into a tuple passed to variable parameters, and therefore, the internal function, directly to the variable args as a tuple like .

The purpose of defining variable parameters but also to simplify the call. Suppose we want to calculate the average value of an arbitrary number, you can define a variable parameter:

def average(*args):
    ...

In this way, when you call, you can write:

1 >>> average()
2 0
3 >>> average(1, 2)
4 1.5
5 >>> average(1, 2, 2, 3, 4)
6 2.4

task

Please write accepts a variable parameter average () function.

 1 def average(*args):
 2     sum = 0.0
 3     if len(args) == 0:
 4         return sum
 5     for x in args:
 6         sum = sum + x
 7     return sum/len(args)
 8 
 9 print average()
10 print average(1, 2)
11 print average(1, 2, 2, 3, 4)

 

Guess you like

Origin www.cnblogs.com/ucasljq/p/11597501.html