Python function

原创转载请注明出处:http://agilestyle.iteye.com/blog/2327737

调用函数

# abs()
print(abs(100))
print(abs(-20))
print(abs(12.34))
# max()
print(max(1, 2))
print(max(2, 3, 1, -5))
# int()
print(int('123'))
print(int(12.34))
# float()
print(float('12.34'))
# str()
print(str(1.23))
print(str(100))
print(isinstance(str(1.23), str))
print(isinstance(str(100), str))
# bool()
print(bool(1))
print(bool(''))

Console Output

定义一个空函数 —— pass

# 空函数 —— 如果想定义一个什么事也不做的空函数,可以用pass语句
def nop():
    pass

参数检查 —— isinstance()

# 参数检查
def my_abs(x):
    if not isinstance(x, (int, float)):
        raise TypeError('invalid data type')
    if x >= 0:
        return x
    else:
        return -x


print(my_abs(-10))
print(my_abs('test'))

Console Output


 

返回多个值

import math


# 函数可以同时返回多个值,但其实就是一个tuple
def move(x, y, step, angle=0):
    a = x + step * math.cos(angle)
    b = y - step * math.sin(angle)
    return a, b


r = move(100, 100, 60, math.pi / 6)
print(r)

Console Output


 

递归函数

# 递归函数
def fact(n):
    if n == 1:
        return 1
    return n * fact(n - 1)

print(fact(1))
print(fact(5))
print(fact(100))

Console Output


Note:

  • 使用递归函数的优点是逻辑简单清晰,缺点是过深的调用会导致栈溢出。
  • 针对尾递归优化的语言可以通过尾递归防止栈溢出。尾递归事实上和循环是等价的,没有循环语句的编程语言只能通过尾递归实现循环。
  • Python标准的解释器没有针对尾递归做优化,任何递归函数都存在栈溢出的问题。 

猜你喜欢

转载自agilestyle.iteye.com/blog/2327737