转载请标明出处:
本文出自:
Python函数
1. Python之调用函数
print abs(100)print abs(-20)print abs(12.34)print cmp(1, 2)print cmp(2, 1)print cmp(3, 3)print int('123')print int(12.34)print str(123)print str(1.23)L = []x = 1while x <= 100: L.append(x * x) x = x + 1print sum(L)
2. Python之编写函数
def square_of_sum(L): sum = 0 for x in L: sum = sum + x * x return sumprint square_of_sum([1, 2, 3, 4, 5])print square_of_sum([-5, 0, 5, 15, 25])
3. Python函数之返回多值
x = (-b±√(b²-4ac)) / 2aimport mathdef quadratic_equation(a, b, c): t = math.sqrt(b * b - 4 * a * c) return (-b + t) / (2 * a),( -b - t )/ (2 * a)print quadratic_equation(2, 3, 0)print quadratic_equation(1, -6, 5)
4. Python之递归函数
def move(n, a, b, c): if n ==1: print a, '-->', c return move(n-1, a, c, b) print a, '-->', c move(n-1, b, a, c)move(4, 'A', 'B', 'C')
5. Python之定义默认参数
def greet(name='world'): print 'Hello, ' + name + '.'greet()greet('Bart')
6. Python之定义可变参数
def average(*args): sum = 0.0 if len(args) == 0: return sum for x in args: sum = sum + x return sum / len(args)print average()print average(1, 2)print average(1, 2, 2, 3, 4)