gpt4 book ai didi

python - 如何修复 'else' 输出超过 1 个结果

转载 作者:行者123 更新时间:2023-12-01 00:56:07 27 4
gpt4 key购买 nike

非常基本的问题,尝试输出一个数字是否可以被 3/5/both/none 整除,但 else 会在不成立时返回 2 个语句。我该如何解决这个问题?

我尝试移动 else 缩进的位置,第一次它不会输出不是 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")

即如果输入 67 您的号码不是预期的 3 或 5 的倍数。但是,如果输入 15,Your number is the multiple of 3 and 5Your number is not a multiple of 3 or 5 就是意外输出。

最佳答案

如果您合并到目前为止的所有评论建议,您会得到如下内容:

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")

关于python - 如何修复 'else' 输出超过 1 个结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56246052/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com