Новый курс! Каждый программист должен знать генеративный ИИ!
Попробуйте бесплатный урок0
Can someone please show me an easy efficient way to handle the exceptions in this code?
I'm trying to make a simple calculator using the new material I've learned. https://code.sololearn.com/cVdJrLkNlZlo/#py
4 ответов
+ 1
def add(x,y):
return x+y
def sub(x,y):
return x-y
def mult(x,y):
return x*y
def div(x,y):
return x/y
x = int(input())
op = input()
y = int(input())
ops = {
'+': add, '-': sub, 'x': mult, '/': div
}
try:
func = ops[op]
result = func(x,y)
print('{0} {1} {2} = {3}'.format(x,op,y,result))
except:
print('Invalid')
if you want to be proper do except KeyError
0
Kamil Hamid thank you. I'm trying to find an efficient way to handle exceptions with x and y as well. I know how to do it with try and except but I'm trying to find a more efficient way to handle them.
0
I'm trying to find an efficient way to handle exceptions with x and y as well. I know how to do it with try and except but I'm trying to find a more efficient way to handle them.
0
1. Which exceptions?
2. Try/except is the way of handling exceptions. What do you want to change?