我不知道为什么循环没有结束,它只是卡在那里。
我对python不太熟悉,这是我的第二个小编程项目。
#Sieve of Eratosthenes
def li(num):
for i in range(2,num+1):
yield i
def main(num):
p = 2
yes = True
rip = 2
main_li = list(li(num))
continues = True
while continues:
while yes:
try:
if main_li[main_li.index(p*rip)]:
print(f"{p} times {rip} exists")
del main_li[main_li.index(p*rip)]
print("and its deleted")
rip += 1
print(f"rip is now {rip}")
except:
print(f"{p} times {rip} dont exist")
while True:
try:
if p * (rip+1) == True:
break
except:
yes = False
print(f"loop for smallest prime: {p}, stops")
rip = 2
print("increment is now back to 2")
break
try:
if main_li[p + 1]:
p += 1
yes = True
except:
continues = False
print(main_li)
num = int(input("What Number You Wish Sieve of Eratosthenes to Execute to: "))
main(num)
并再一次堆栈溢出决定说:“看起来你的帖子主要是代码;请添加更多细节”
发布于 2018-12-17 09:26:40
没有人想要解决这个问题,看起来有点痛苦。
对你的问题最可能的答案涉及制造continues
变量的有缺陷的方法False
。continues
总有可能是这样True
。找出原因,你可能会得到你的问题的答案。
作为一般编程注释,您可以使用泛型捕获所有异常,except
而不是捕获特定异常。你的try / except应该看起来更像这样:
try:
a = b[0]
except KeyError:
a = 0
您的try
块中有太多代码,块中的代码太多except
。使嵌套在每个代码中的代码尽可能小,以便您可以在非常特定的情况下采取非常具体的操作。这允许您的应用程序适当地响应不同的错误类型。如果您需要捕获多个异常类型,那么您也可以这样做:
try:
a = b[0]
except (KeyError, IndexError):
a = 0
except ValueError:
a = None
我意识到上面的内容有点荒谬,但它显示了如何根据错误定制输出。
附加说明有例外,嵌套两个通用except
块...坏主意。仅仅因为Python没有抱怨并不意味着它是一个好主意。
发布于 2018-12-17 10:04:43
有些部分已经重新安排,但大部分保持不变。它仍然循环p*rip
(2 * 2 => num * num)并从中删除main_li
:
#Sieve of Eratosthenes
def li(num):
for i in range(2,num+1):
yield i
def main(num):
p = 2
yes = True
rip = 2
main_li = list(li(num))
continues = True
while continues:
if (p > num):
break
print(f"loop for smallest prime: {p}, stops")
rip = 2
print("increment is now back to 2")
while yes:
if (rip > num):
break
try:
print(f"{p} times {rip} exists")
main_li.remove(p*rip)
print("and its deleted")
except (ValueError, IndexError):
print(f"{p} times {rip} dont exist")
rip+=1
print(f"rip is now {rip}")
p+=1
print(main_li)
while True:
num = int(input("What Number You Wish Sieve of Eratosthenes to Execute to (-1 to Quit): "))
if (num == -1):
break
main(num)
https://stackoverflow.com/questions/-100006297
复制相似问题