当我用x = 5测试除法时,y = 32因此,除法函数不起作用。
这是不可能的:' 1/0' ,因为我添加了'尝试& amp;除外'之后它返回float(x)/ float(y)'不工作。
import math
def control(a,x,y,z,k):
return {
'ADDITION': addition(x, y),
'SUBTRACTION': subtraction(x, y),
'MULTIPLICATION': multiplication(x, y),
'DIVISION': division(x, y),
'MOD': modulo(x, y),
'SECONDPOWER': secondPower(x),
'POWER': power(x, y),
'SECONDRADIX': secondRadix(x),
'MAGIC': magic(x, y, z, k)
}
def addition(x, y):
return float(x) + float(y)
def subtraction(x, y):
return float(x) - float(y)
def multiplication(x, y):
return float(x) * float(y)
def division(x, y):
if(y != 0):
return float(x) / float(y)
else:
raise
return ValueError("This operation is not supported for given input parameters")
if (x!= 0 or y!= 0):
return float(x) / float(y)
def modulo(x, y):
if (x % 2) == 0:
print("This operation is not supported for given input parameters")
else:
return float(x) % float(y)
def secondPower(x):
return math.pow(float(x),2.0)
def power(x, y):
return math.pow(float(x),float(y))
def secondRadix(x):
return math.sqrt(float(x))
def magic(x, y, z, k):
l = float(x) + float(k)
m = float(y) + float(z)
try:
control(a,x,y,z,k)
except ValueError:
print("This operation is not supported for given input parameters")
out = control(a,x, y, z, k)
print(out)
我在这段代码中做错了什么?我是Python的初学者。
答案 0 :(得分:0)
这里需要修复一些错误。首先,您将覆盖除法函数中的参数:
def division(x, y):
try:
x = 0 #now x is 0 regardless of what you passed in
y = 0 #same for y
然后在这一行:
if (x!= 0 or y!= 0):
如果x不为0,则为真,因为如果任何条件为真,or
操作将返回true。因此,例如,如果您有x = 1且y = 0,则仍然执行无效除法。您可以通过仅检查y != 0
来解决此问题。
更好的方法是让python执行除法并捕获在您尝试进行无效除法时引发的ZeroDivisionError:
def division(x, y):
try:
return x/y
except ZeroDivisionError:
print("This operation is not supported for given input parameters")
这更符合"Easier to ask for forgiveness than permission"的整体Python哲学。