Python for 循环以不满足条件结束

标签 python python-3.x

我有一个程序,它要求用户输入两个数字,并检查这两个数字之间的每个数字是否都可以被 5 和 7 整除。 如果范围内的数字不能被 5 和 7 除,我希望程序输出类似“找不到数字”的内容。 例如,如果用户输入 3 和 4,它将打印“No number found”

我尝试了几种不同的方法,但都没有用。

start = int(input("Start: "))
stop = int(input("Stop: "))


for number in range(start, (stop+1),1):
    if number % 5 == 0 and number % 7 ==0:
        print("Number", number, "can be divided with 5 and 7")
        print("Stop search")
        break
    elif  number % 5 == 0 and number % 7 !=0:
        print(number, "can't be divided with 7, next.")
    elif number % 5 != 0:
        print(number,"can't be divided with 5, next.")

最佳答案

您可以将 else: 子句与 for 循环一起使用。它仅在整个 for 循环正常结束并且没有到达 break 子句时执行。在极少数情况下它很有用!

for number in range(start, (stop+1),1):
    if number % 5 == 0 and number % 7 ==0:
        print("Number", number, "can be divided with 5 and 7")
        print("Stop search")
        break
    elif  number % 5 == 0 and number % 7 !=0:
        print(number, "can't be divided with 7, next.")
    elif number % 5 != 0:
        print(number,"can't be divided with 5, next.")
else:
    print("No number that can be divided by both 5 and 7 found.")

关于Python for 循环以不满足条件结束,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58081508/

相关文章:

python-3.x - 如何在 xarray 中组合具有不同尺寸大小的多个数据集(.h5 文件)

python - 滚动窗口重新访问 - 添加窗口滚动数量作为参数 - 前瞻分析

python - Python 中列表维度的减少

python - 在 python shell 中, "b"字母不起作用,什么?

Python - 将列表转换为列表列表,每个条目包含唯一组合

python - 无模块名称,下划线导入

mysql - 优化 SQLAlchemy 中的hybrid_properties

python - 每次求和通过某个阈值时如何重新采样?

Python 编码问题(ascii 转 utf-8)

python - Scrapy - 递归抓取到第三页