Python 我可以让for循环运行整个范围吗?
这是我的密码。我试图找到输入整数之前或等于整数的素数。然而,当循环看到符合要求的范围内的整数时,它似乎停止了。不幸的是,这不是我想要的。在做出判断之前,我想让它通过范围内的所有测试。这可能吗?如果是,我该怎么做?多谢各位Python 我可以让for循环运行整个范围吗?,python,loops,Python,Loops,这是我的密码。我试图找到输入整数之前或等于整数的素数。然而,当循环看到符合要求的范围内的整数时,它似乎停止了。不幸的是,这不是我想要的。在做出判断之前,我想让它通过范围内的所有测试。这可能吗?如果是,我该怎么做?多谢各位 def getNumber(main): n = int(input()) return n def isPrime(n): list=[2] if n > 1: for i in range(2, n+1):
def getNumber(main):
n = int(input())
return n
def isPrime(n):
list=[2]
if n > 1:
for i in range(2, n+1):
for a in range (2, n):
if i*a != i and i%a != 0 and i%2 != 0:
list.append(i)
break
return "\n".join(map(str, list))`
def main():
n = getNumber(main)
print(isPrime(n))
main()
你的逻辑有点错误。下面是您的代码所做的:
2
到输入的n
的递增顺序检查数字i
,检查2
和n
之间是否有任何数字a
除以i
a
除以i
,则将i
添加到列表中,然后移动到下一个i
def getPrimesLessThanOrEqualTo(n):
if n <= 1: # Anything 1 or less has no primes less than it.
return "" # So, return nothing.
list = [2] # 2 is the lowest prime number <= n
for i in range(3, n+1): # We start at 3 because there's no need to re-check 2
for a in list: # Instead of iterating through everything less than
# i, we can just see if i is divisible by any of
# the primes we've already found
if i % a == 0: # If one of the primes we've found divides i evenly...
break # then go ahead and try the next i
list.append(i) # Now, if we got through that last bit without
# hitting the break statement, we add i to our list
return "\n".join(list) # Finally, return our list of primes <= i
def getPrimesLessThanOrEqualTo(n):
如果n您可以使用if/else
块,如果您的break
从未被iterable中的任何项执行,则将触发else
语句<代码>4.4
演示了如何完成这项几乎完全相同的任务
n = int(input('Enter number: '))
if n <= 1:
print('No primes')
else:
primes = []
for i in range(2, n +1):
for k in range(2, i):
if not i % k:
break
else:
primes.append(i)
print(*primes)
# Enter number: 50
# 2 3 5 7 11 13 17 19 23 29 31 37 41 43 47
n=int(输入('输入编号:'))
如果你能举个更好的例子吗?循环运行整个范围,除非你打破它。不要将变量命名为list
谢谢您的帮助。我知道我有一些逻辑错误。你对如何改进Python中的逻辑有什么建议吗?好吧,如果我可以坦率地说,Python不是问题所在——同样的问题也会在任何其他编程语言中出现。我的建议是,只需事先写出你想要使用的算法,用伪代码,甚至只用文字,然后手动按照它来操作,以确保它按照你想要的方式运行。然后,在那之后,在代码中实现它并测试它,以确保它仍然按照您希望的方式工作。谢谢您的建议。我一定会尝试一下。