r_metal r_metal - 3 months ago 10
Python Question

Function keeps doing the same thing

This program suppose to find 1000 prime numbers and pack them into a list

Here's the code:

num = raw_input('enter a starting point')
primes = [2]
num = int(num)
def prime_count(num):

if num % 2 == 0: #supposed to check if the number is divided by 2 evenly
num = num +1 #if it is, then add 1 to that number and check again
return num

elif num % num == 0:
primes.append(num) #supposed to add that prime to a list
num = num + 1 #add 1 and check again
return num

while len(primes) <= 999:

So what actually happens when I run it:
it asks me raw_input and then goes to various things depending on what I choose as input:

  • If I choose a prime, let's say 3, it runs and adds 999 of 3s to the list instead of adding it just one time and going on to try 4

  • If I choose a non-prime, let's say 4, it just breaks, after that I can't even print out a list

What am i doing wrong?


You're never using the return value from prime_count. Try this:

while len(primes) <= 999:
    num = prime_count(num)

You've set your self up for confusion by using the name num as both a parameter (also a local variable) inside of prime_count, and also as a global variable. Even though they have the same name, they are different variables, due to Python's rules for the scope of variables.

Also, prime_count is (probably unintentionally) leveraging the fact that primes is a global variable. Since you're not assigning to it, but rather just calling a method (append), the code will work without using the global keyword.

However, your algorithm isn't even correct. if num % num == 0 says "if a number divided by itself has a remainder of zero" which will always be true. This program will find a lot of "primes" that aren't primes.

Real Python programs do very little in the global scope; your current code is just asking for confusion. I suggest you start with this template, and also do some reading of existing Python code.

def add_three(a_param):
    a_local_var = 3       # This is *different* than the one in main!
                          # Changes to this variable will *not* affect
                          # identically-named variables in other functions

    return a_local_var + a_param

def main():
    a_local_var = 2

    result = add_three(a_local_var)

    print result    # prints 5

if __name__ == '__main__':