def average(*args):
sum = 0
if len(args) == 0:
print('Error')
for i in args:
sum += i
avg = sum / len(args)
return avg
print average()
很简单啊,只打印不返回,那就会继续执行下去。那到了用len(args)时len(args)=0为除数就报错了。我记得前面的章节9-2有讲:return表示返回的意思,函数体内部的语句在执行时,一旦执行到return时,函数就执行完毕,并将结果返回。
所以懂了么
def average(*args): sum = 0 if len(args) == 0: print('Error') for i in args: sum += i avg = sum / len(args) return avg average()