虽然循环在 Python 中无法正常工作 [英] While loop not working properly in Python

查看:32
本文介绍了虽然循环在 Python 中无法正常工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我试图找到第 6 个质数,而 getPrime 中的 while 循环无法正常工作.它应该在 count 大于 num 时结束,但事实并非如此.如果你能帮我找出原因就好了.

So I am trying to find 6th prime number, and the while loop in getPrime is not working properly. It is supposed to end when count is bigger than num, but it doesn't. It'd be great if you could help me find out why.

import math

def isPrime(num):
    if num == 1:
        return False
    if num % 2 == 0 and num > 2:
        return False
    for i in range(3, int(math.sqrt(num))+1, 2):
        if num % i == 0:
            return False
    return True

def getPrime(num):
    count = 1
    while count < num:
        for i in range(1, 20):
            #print "check"
            if isPrime(i):
                print "prime", i
                count += 1
                print "count", count
            else:
                continue
    print i
    return i

getPrime(6)

推荐答案

您只是在 for 循环结束时检查 count 的值,因此您将始终以 1-20 的完整范围进行测试.为什么范围限制为 20?

You're only checking the value of count at the end of the for loop so you will always end up with the full range of 1-20 being tested. Why is the range limited to 20?

您根本不需要 for 循环.使用 while 循环不断寻找素数,直到您拥有 num 个素数.

You don't need a for loop at all. Use the while loop to keep finding primes until you have num of them.

尝试类似:

def getPrime(num):
    count = 0 
    i = 1 
    highPrime = None 
    while count < num:
        if isPrime(i):
            count += 1
            highPrime = i 
        i += 1
    return highPrime

这篇关于虽然循环在 Python 中无法正常工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆