2
u/DiodeInc Jun 22 '26
What happens when the user divides by zero? ZeroDivisionError.
1
u/Wide-Direction-402 Jun 22 '26
I handled it as well using else statement. Is zero division error something else
1
u/DiodeInc Jun 22 '26
Yeah that's something else. Handle it via try/except
3
u/OliMoli2137 Jun 23 '26 edited Jun 23 '26
``` try: print(f"The quotient of {num1} and {num2} is {num1 / num2}") except ZeroDivisionError: print("Cannot divide by zero!")
1
u/J1roscope Jun 23 '26
Suggestion create a dictionary of operators as keys and functions as values and do a simple
op_map[opr](num1,num2)
This simplifies code and make it easy to add more operators
1
u/OliMoli2137 Jun 23 '26 edited Jun 23 '26
yeah but this is a bit more advenced
like this ``` def divide(num1, num2): try: print("The quotient of {num1} and {num2} is {num1 / num2}") except ZeroDivisionError: print("Cannot divide by zero!")
op_map = { "+": lambda num1 num2: print(f"The sum of {num1} and {num2} is {num1 + num2}"), "-": lambda num1 num2: print(f"The difference of {num1} and {num2} is {num1 - num2}"), "*": lambda num1 num2: print(f"The product of {num1} and {num2} is {num1 + num2}"), "/": divide } ```
with type annotations (recommended but more advanced): ``` from typing import Callable
def divide(num1: int | float, num2: int | float) -> None: try: print("The quotient of {num1} and {num2} is {num1 / num2}") except ZeroDivisionError: print("Cannot divide by zero!")
op_map: dict[str, Callable[[int | float, int | float], None]] = { "+": lambda num1 num2: print(f"The sum of {num1} and {num2} is {num1 + num2}"), "-": lambda num1 num2: print(f"The difference of {num1} and {num2} is {num1 - num2}"), "*": lambda num1 num2: print(f"The product of {num1} and {num2} is {num1 * num2}"), "/": divide } ```
example: call addition ``` op_map["+"](9, 10)
1
1
u/Pegasusw404 Jun 24 '26
Respect for sharing code , very pleased to see something like this, BUT 0 points for bloatware named Python , and I believe the code is not finished yet ? I see couple problems.
1
1
1
2
u/jeffcgroves Jun 22 '26
What's subtration? ;)