Python 如何创建查找可被7整除但不能被5整除的数字的函数

Python 如何创建查找可被7整除但不能被5整除的数字的函数,python,python-3.x,function,Python,Python 3.x,Function,我正在尝试编写一个名为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 () 我有正确的参数吗?我到底要回

我正在尝试编写一个名为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))

逻辑上有几点错误:

它将只打印最后找到的值 return语句不正确 如果该范围内没有数字怎么办 我会这样修改它:

In [1]: def find_numbers(L, U):
...:     r = []
...:     for i in range(L, U):
...:         if i % 7 == 0 and i % 5 != 0:
...:             r.append(i)
...:     if not r:
...:         return None
...:     else:
...:         return r
...:

为此,您可以使用简单的列表理解

result = [x for x in range(lower_bound, upper_bound) if x % 7 == 0 and x % 5 != 0]
如果您想让它变得更优雅、更可重用,可以将其封装在函数中

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


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

可以看出,这种列表理解方法的运行速度比传统的循环解决方案快一点。

您可以将其视为模式、偏移量,而不是上下限


7*5=35=>你将有一个长度为35的调和模式,其中7、14、21、28是你感兴趣的数字,35是你跳过的数字。加上n*35作为偏移量,你手上就有无穷大,r+=[i]可以更清晰地写为r.appendi。你目前有两个问题,都是初级课程问题/家庭作业。你们两个都找到了解决办法,恭喜你们。所以不要给我家庭作业服务——你错过了一个利用简单问题学习python基础知识的好机会:实验。当你的任务变得更困难时,你需要这些基础知识。试着自己解决它们。谢谢。我试过了,但有时我需要帮助。正如你所看到的,我已经编写了代码,但是我被卡住了。
def find_numbers(lower_bound, upper_bound):
    return [x for x in range(lower_bound, upper_bound) if x % 7 == 0 and x % 5 != 0]


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