函数

2017-03-28  本文已影响0人  折叠小猪

调用函数

# 调用函数abs
>>> abs(-20)
20

调用函数的时候,如果传入的参数数量不对或者参数类型不能被函数所接受,会报TypeError的错误。

定义函数

  1. 定义一个函数要使用def语句,依次写出函数名、括号、括号中的参数和冒号:,然后,在缩进块中编写函数体,函数的返回值用return语句返回。
def my_abs(x):
    if x >= 0:
        return x
    else:
        return -x
def nop():
        pass
if age >= 18:
        pass
def my_abs(x):
    if not isinstance(x, (int, float)):
        raise TypeError('bad operand type')
    if x >= 0:
        return x
    else:
        return -x

内置函数isinstance文档

import math
def move(x, y, step, angle=0):
        nx = x + step * math.cos(angle)
        ny = y - step * math.sin(angle)
        return nx, ny
>>> x, y = move(100, 100, 60, math.pi / 6)
>>> print(x, y)
151.96152422706632 70.0
# Python函数返回的仍然是单一值
>>> r = move(100, 100, 60, math.pi / 6)
>>> print(r)
(151.96152422706632, 70.0)
# -*- coding: utf-8 -*-
import math
def quadratic(a, b, c):
        if not intOrFloat(a) or not intOrFloat(b) or not intOrFloat(c):
            raise TypeError('bad operand type')
        delta = b*b-4*a*c
        if delta < 0:
            return "无实根"
        else:
            x1 = (-b+math.sqrt(delta))/(2*a)
            x2 = (-b-math.sqrt(delta))/(2*a)
            if x1 == x2 and delta == 0:
                return x1
            else:
                return x1, x2
def intOrFloat(a):
        return isinstance(a, (int, float))
print(quadratic(2, 3, 1))
print(quadratic(5, 0, 25))
print(quadratic(1, 2, 1))

函数的参数

上一篇 下一篇

猜你喜欢

热点阅读