python - Function keeps doing the same thing -
this program suppose find 1000 prime numbers , pack them list
here's code:
num = raw_input('enter starting point') primes = [2] num = int(num) def prime_count(num): if num % 2 == 0: #supposed check if number divided 2 evenly num = num +1 #if is, add 1 number , check again return num elif num % num == 0: primes.append(num) #supposed add prime list num = num + 1 #add 1 , check again return num while len(primes) <= 999: prime_count(num) so happens when run it: asks me raw_input , goes various things depending on choose input:
- if choose prime, let's 3, runs , adds 999 of 3s list instead of adding 1 time , going on try 4
- if choose non-prime, let's 4, breaks, after can't print out list
what doing wrong?
update: fixed it, when run i'm getting error (typeerror: unsupported operand type(s) %: 'nonetype' , 'int')
number = raw_input('enter starting point') primes = [2] number = int(number) def prime_count(x): if x % 2 == 0: #supposed check if number divided 2 evenly number = x +1 #if is, add 1 number , check again return number else: in range(3, x-1): if x % == 0: primes.append(x) #supposed add prime list number = x + 1 #add 1 , check again return number while len(primes) <= 999: number = prime_count(number)
you're never using return value prime_count. try this:
while len(primes) <= 999: num = prime_count(num) you've set self confusion using name num both parameter (also local variable) inside of prime_count, , global variable. though have same name, different variables, due python's rules scope of variables.
also, prime_count (probably unintentionally) leveraging fact primes global variable. since you're not assigning it, rather calling method (append), code work without using global keyword.
however, algorithm isn't correct. if num % num == 0 says "if number divided has remainder of zero" always true. program find lot of "primes" aren't primes.
real python programs little in global scope; current code asking confusion. suggest start template, , reading of existing python code.
def add_three(a_param): a_local_var = 3 # *different* 1 in main! # changes variable *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__': main()
Comments
Post a Comment