Untitled
unknown
plain_text
a month ago
1.1 kB
3
Indexable
''' This is a function to perform calculations (addition, subtraction, multiplication and division) It accepts three parameters: a, b, op. a: first number b: second number op: type of operation In case of division by zero it raises an error. The function returns a number or None ''' def calc(a, b , op): # If add operation we sum the elements if op == 'add': return a + b # If sub operation we subtract the elements elif op == 'sub': return a - b # If mul operation we multiply the elements elif op == 'mul': return a * b # If div operation we divide the elements elif op == 'div': # If dividing by zero we raise an error if b == 0: raise ValueError("Division by zero") # Otherwise we return the result return a / b else: # If we don't provide an operation we return None return None # Examples print(calc(4, 3, "add")) # 7 print(calc(4, 3, "sub")) # 1 print(calc(4, 3, "mult")) # 12 print(calc(4, 3, "div")) # 1.33333 print(calc(4, 3, "")) # None
Editor is loading...
Leave a Comment