一旦我用python打印了一定数量的数字,有没有办法停止我的循环?

一旦我用python打印了一定数量的数字,有没有办法停止我的循环?,python,Python,我正在用Python创建一个代码来获取第10001个素数,我正在寻找一种方法,在打印了10001个数字后停止打印数字。这可能吗?您可以在for循环中添加一个中断,它将退出循环。您必须在10001之后包含if/then语句以breakwhile循环在这里工作: primes = [] while len(primes) < 10001: #some code to find and print the next prime primes.append(next_prime)

我正在用Python创建一个代码来获取第10001个素数,我正在寻找一种方法,在打印了10001个数字后停止打印数字。这可能吗?

您可以在for循环中添加一个
中断
,它将退出循环。您必须在10001之后包含if/then语句以
break
while循环在这里工作:

primes = []
while len(primes) < 10001:
    #some code to find and print the next prime
    primes.append(next_prime)
primes=[]
而len(素数)<10001:
#找到并打印下一个素数的代码
素数。追加(下一个素数)

是的,您可以在循环之前创建一个变量,每次它得到一个素数时,您向它添加1,然后检查它是否已经是打破循环的第10001个数字。或者甚至类似的事情:

currentPrime = 0
while currentPrime < 10001:
    #Do your checks here to see if it's a prime, and if it is, do the following code:
    currentPrime = currentPrime + 1
currentPrime=0
当currentPrime<10001时:
#在此处执行检查以查看它是否为素数,如果为素数,请执行以下代码:
currentPrime=currentPrime+1

有很多方法可以做到这一点,所以只要找到一种更适合您的方法。

这是任何编程语言最基本的功能。提示:“+=1”和“如果”可能重复您可以使用的语句。