Не работает проверка if до словаря
Когда применяю данную проверку здесь - она не работает.
first, second, operation = float(input()), float(input()), input()
Сomputation = {
"+": first + second,
"-": first - second,
"*": first * second,
"/": first / second,
"mod": first % second,
"pow": first ** second,
"div": first // second
}
Status = False
for keys in Сomputation.keys():
if operation == keys:
Status = True
if (second == 0 or first == 0) and (operation == "/" or operation == "div" or operation == "mod"):
print("Division by 0!")
else:
print(Сomputation[keys])
if Status != True:
print("Do not work")
Но когда пишу так, то проверка срабатывает корректно.
first, second, operation = float(input()), float(input()), input()
if (second == 0 or first == 0) and (operation == "/" or operation == "div" or operation == "mod"):
print("Division by 0!")
exit(0)
Сomputation = {
"+": first + second,
"-": first - second,
"*": first * second,
"/": first / second,
"mod": first % second,
"pow": first ** second,
"div": first // second
}
Status = False
for keys in Сomputation.keys():
if operation == keys:
Status = True
print(Сomputation[keys])
if Status != True:
print("Do not work")
Спросив у знакомого, более опытного человека, он объяснил это тем, что в словаре выполняется ранее, чем проходит проверка. Но, саму то инструкцию я даю после словаря. Так-же буду видеть код, который Вы считаете альтернативой этому.
Ответы (1 шт):
У вас значения словаря уже выполнились.
Чтобы можно было выполнять код из значения словаря, его нужно сделать вызываемым, например, через лямбды
Пример:
first, second, operation = float(input()), float(input()), input()
# <<<<<<<<<<<<
Сomputation = {
"+": lambda first, second: first + second,
"-": lambda first, second: first - second,
"*": lambda first, second: first * second,
"/": lambda first, second: first / second,
"mod": lambda first, second: first % second,
"pow": lambda first, second: first ** second,
"div": lambda first, second: first // second
}
# <<<<<<<<<<<<
Status = False
for keys in Сomputation.keys():
if operation == keys:
Status = True
if (second == 0 or first == 0) and operation in ("/", "div", "mod"):
print("Division by 0!")
else:
print(Сomputation[keys](first, second)) # <<<<<<<<<<<<
if Status != True:
print("Do not work")
PS.
Проверку operation == "/" or operation == "div" or operation == "mod" можно упросить, если значение поместить, например, в кортеж и проверить наличие operation в нем, т.е.:
operation in ("/", "div", "mod")
PPS.
Код можно упростить:
first, second, operation = float(input()), float(input()), input()
# Сразу проверяем допустимость операции
if (second == 0 or first == 0) and operation in ("/", "div", "mod"):
print("Division by 0!")
exit()
Сomputation = {
"+": lambda first, second: first + second,
"-": lambda first, second: first - second,
"*": lambda first, second: first * second,
"/": lambda first, second: first / second,
"mod": lambda first, second: first % second,
"pow": lambda first, second: first ** second,
"div": lambda first, second: first // second
}
# Если операции нет в словаре
if operation not in Сomputation:
print("Do not work")
exit()
# Достаем лямбду по операции и выполняем ее
print(Сomputation[operation](first, second))