Menu
Coddy logo textTech

מספר יחיד

שיעור 7 מתוך 29 בקורס פרויקט מחשבון באמצעות Python של Coddy.

נכון לעכשיו, הפונקציה calc תומכת רק בפעולות עם שני מספרים.

בואו נוסיף פעולות עם מספר יחיד עבור '+' ו-'-',

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

אתגר

קל

הוסיפו תמיכה באופרטורים של מספר יחיד עבור '+' ו-'-'.

  • הוסיפו ערך ברירת מחדל, None, לארגומנט ה-3rd של calc

נסו בעצמכם

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 אונליין