首页 > 解决方案 > 如何创建一个函数来查找可被 7 整除但不能被 5 整除的数字

问题描述

我正在尝试编写一个名为 find_numbers 的函数,该函数将找到所有可被 7 整除而不是 5 的数字。

我的问题是到目前为止的实际功能:

def find_numbers(lower_bound, upper_bound):
    for i in range(lower_bound,upper_bound):
        if (i % 7 == 0 and i % 5 !=0):
            print(i)

return ()

我有正确的参数吗?我到底要返回什么?我觉得我接近正确的解决方案,但我真的被卡住了:(它正在打印出我想要的东西,有点,但不正确。非常感谢任何帮助!!谢谢大家。

lower_bound = int( input("Lower bound to search for numbers: ") )
upper_bound = int( input("Upper bound to search for numbers: ") )

found_numbers = find_numbers(lower_bound, upper_bound)

print("The numbers that are divisible by 7 but not by 5 
are:\n{}".format(found_numbers))

标签: pythonpython-3.xfunction

解决方案


def find_numbers(lower_bound, upper_bound):
    results=[]
    for i in range(lower_bound,upper_bound):
      if (i % 7 == 0 and i % 5 !=0):
          results.append(i)
    return results

lower_bound = int( input("Lower bound to search for numbers: ") )
upper_bound = int( input("Upper bound to search for numbers: ") )

found_numbers = find_numbers(lower_bound, upper_bound)

print("The numbers that are divisible by 7 but not by 5 
are:\n{}".format(found_numbers))

推荐阅读