简体   繁体   中英

Nothing happens when I run this prime factors program

Beginner here. I run this Python code that's supposed to find and print the prime factors of any number (in this case it is 16), but nothing comes up in the console. Help!

def is_not_prime(x):
    for i in range(2,x):
        if x % i == 0:
            return True
            break
        else:
            return False

def prime_factors(n):
    for i in range(2,n):
        if n % i == 0:
            x = i
            primes.append(x)
            break
        y = n / x
        return y

primes = []

def main(y):
    while is_not_prime(y):
        prime_factors(y)
    primes.append(y)
    print(primes)

main(16)

Look at this:

while is_not_prime(y):
    prime_factors(y)

16 is not prime so you are stuck in an infinite while True loop here.

If you want to break out of this loop, you are going to need to change y inside the loop somehow.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM