我该如何检查代码中显示的除法的答案是否可以被2整除



我的目标是检查b/a的答案是否可被2整除,如果是,它将打印"是"。

a = int(input())
b = int(input())
if b / a #is divisible by 2
print("Yes.")
else:
print("No.")

这个怎么样?

a = int(input())
b = int(input())
if (b / a) % 2 == 0:
print("yes")
else:
print("no")

使用模(%(,因此对于本例if (b/a)%2 == 0:

您还可以使用ternary operator将if/else语句组合成一个单独的打印语句,如下所示:

print("yes" if (b / a) % 2 == 0 else "no")

您也可以以无分支的方式来降低复杂性并提高速度:

print("yes" * ((b/a) % 2 == 0) + "no" * (not (b/a) % 2 == 0))

这是因为Falseint值为0,因此为"text" * False = ""
类似地,"text" * True = "text"

最新更新