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

标签 python

非常基本的问题,尝试输出一个数字是否可以被 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/

相关文章:

python:对我的复制变量的更改会影响原始变量

python - 正则表达式查找搜索词并将结果放入另一个数据文件中?

python - django 生产服务器是否推荐使用 virtualenv?

python - python中关于or的正则表达式

python - 为什么 splatting 在 rhs 上创建一个元组,但在 lhs 上创建一个列表?

python - Bottle 版本 Python Web 框架

python - 用 python 中可能的字典列表展平嵌套字典

python - Headless Python Selenium MacOS 通过 Chromium 单击/下载文档

python - 为什么 `tkinter.ttk.Notebook`标签越来越薄?

python - 从 Facebook 相册中获取点赞数