מספר יחיד
שיעור 7 מתוך 29 בקורס פרויקט מחשבון באמצעות Python של Coddy.
נכון לעכשיו, הפונקציה calc תומכת רק בפעולות עם שני מספרים.
בואו נוסיף פעולות עם מספר יחיד עבור '+' ו-'-',
calc('+', 5.4)->5.4calc('-', 3)->-3
אתגר
קלהוסיפו תמיכה באופרטורים של מספר יחיד עבור '+' ו-'-'.
- הוסיפו ערך ברירת מחדל,
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 אונליין