Menu
CoddyTech

单个数字

Coddy Python 计算器项目 课程的第 7 课,共 29 课。

目前,calc 函数仅支持两个数字的运算。

我们来为 '+' 和 '-' 添加单个数字的运算:

  • calc('+', 5.4)  ->  5.4
  • calc('-', 3)  ->  -3
challenge icon

挑战

简单

为单个数字支持 '+' 和 '-' 运算符。

  • 为 calc 的第 3 个参数添加默认值 None

亲手试试

def calc(op, n1, n2):
    if not isinstance(n1, int) and not isinstance(n1, float):
        raise Exception('Invalid number "' + str(n1) + '"')
    if not isinstance(n2, int) and not isinstance(n2, float):
        raise Exception('Invalid number "' + str(n2) + '"')

    if op == '+' or op == 'add':
        return n1 + n2
    if op == '-' or op == 'sub':
        return n1 - n2
    if op == '*' or op == 'mul':
        return n1 * n2
    if op == '/' or op == 'div':
        if n2 == 0:
            raise Exception("Division by zero")
        return n1 / n2
    if op == '%' or op == 'mod':
        if n2 == 0:
            raise Exception("Division by zero")
        return n1 % n2
    if op == '^' or op == 'pow':
        return n1 ** n2

    raise Exception('Invalid operator "' + op + '"')

Python 计算器项目中的所有课

自己练习: Python 在线编译器