一个非常基本的问题,如果一个数字可被3/5 / both / none整除,则尝试输出,但是当它们不为真时将返回2条语句。我该如何解决?
我试图移动其他缩进的位置,第一次它不会输出不是3或5的倍数的数字,第二次它将输出两个答案。
while True:
z = input("Please enter a number- to end the program enter z as -1 ")
if z % 3 == 0 and z % 5 ==0:
print("Your number is a multiple of 3 and 5")
elif z % 3 == 0 and z % 5 != 0:
print("Your number is a multiple of 3")
elif z % 3 != 0 and z % 5 ==0:
print("Your number is a multiple of 5")
if z == -1:
break
else:
print("Your number is not a multiple of 3 or 5")
即如果按预期输入Your number is not a multiple of 3 or 5
,则输入67。但是,如果输入Your number is a multiple of 3 and 5
到15,并且Your number is not a multiple of 3 or 5
是意外输出。
答案 0 :(得分:2)
如果您到目前为止已纳入所有评论建议,则会得到以下信息:
while True:
z = input("Please enter a number- to end the program enter z as -1 ")
# cast to int
z = int(z)
# break early
if z == -1:
break
elif z % 3 == 0 and z % 5 == 0:
print("Your number is a multiple of 3 and 5")
elif z % 3 == 0:
print("Your number is a multiple of 3")
elif z % 5 == 0:
print("Your number is a multiple of 5")
else:
print("Your number is not a multiple of 3 or 5")
答案 1 :(得分:0)
通过启动新的if
块,您将结束前面的elif
链。
if z == -1:
break
else:
print("Your number is not a multiple of 3 or 5")
正如@Daniel Junglas的评论所说,您应该像这样构造它:
z = input("Please enter a number- to end the program enter z as -1 ")
if z == -1:
break
elif (z % 3 == 0) and (z % 5 == 0):
print("Your number is a multiple of 3 and 5")
elif (z % 3 == 0) and (z % 5 != 0):
print("Your number is a multiple of 3")
elif (z % 3 != 0) and (z % 5 == 0):
print("Your number is a multiple of 5")
else:
print("Your number is not a multiple of 3 or 5")