有什么方法可以缩短这段代码吗?

时间:2017-08-24 16:27:47

标签: python divide-by-zero

我今天创建了这行代码,用于确定数字是否均匀划分

if (numerator / denominator * denominator) == numerator:
    print "Divides evenly!"
else:
    print "Doesn't divide evenly."

然而,当我除以0时遇到了一个问题,因为我仍然希望它告诉我,即使分母是0,通过查看分子并查看它是偶数还是奇数,它是否会分裂。我想出了这个:

if denominator != 0 and (numerator / denominator * denominator) == 
numerator:
    print "Divides evenly!"
elif denominator == 0 and numerator % 2 == 0:
    print "Divides evenly!"
else:
    print "Doesn't divide evenly."

有没有办法缩短这个?另外,有没有办法不必添加新的'elif'语句?

2 个答案:

答案 0 :(得分:3)

简而言之,如果denominator0,您希望它为2

if denominator == 0:
    denominator = 2

if numerator % denominator == 0:
    print "Divides evenly!"
else:
    print "Doesn't divide evenly."

甚至更短:

if numerator % (denominator or 2) == 0:
    print "Divides evenly!"
else:
    print "Doesn't divide evenly."

答案 1 :(得分:0)

def fun(n,d):
    return (d==0 and n%2==0) or (d!=0 and n%d==0)