python - Iterating until a function returns True a user defined number of times -


i've written function, isprime(n), returns true if number prime , false if not. able loop function defined number of times; can't figure out how iterate until finds x number of primes. feel though have decent understanding of , while loops, confused how 1 integrates boolean return values loops. here current code , error:

error result:

input:100 traceback (most recent call last): file "euler7.py", line 25, in <module> primelist += 1 typeerror: 'int' object not iterable 

and code:

def isprime(n):     x = 2     while x < sqrt(n):         if n % x == 0:             return false         else:             x += 1     return true  userinput = int(raw_input('input:'))  primelist = [] primesfound = 0  while primesfound != userinput:     = 2     if isprime(i):         primelist.append(i)         primelist += 1         += 1     else:         += 1 

edit (including updated , functioning code):

from math import sqrt def isprime(n):     x = 2     while x < (sqrt(n) + 1):         if n % x == 0:             return false         else:             x += 1     return true  userinput = int(raw_input('input:')) primelist = [] primelist.append(2)  = 2 while len(primelist) != userinput:     if isprime(i):         primelist.append(i)         += 1     else:         += 1  print 'result:', primelist[-1] 

as others have pointed out:

  • you should increment primesfound, not primelist.
  • the isprime() function has bug -- , returns true 9. need sqrt(n) + 1.

in addition:

  • you need initialize i outside while loop; otherwise, build list of 2's.
  • there no need primesfound. check len(primelist).

and pet peeve:

  • command-line programs should resort interactive user input in special circumstances. possible, take parameters command-line arguments or options. example: userinput = int(sys.argv[1]).

Comments

Popular posts from this blog

linux - xterm copying to CLIPBOARD using copy-selection causes automatic updating of CLIPBOARD upon mouse selection -

c++ - qgraphicsview horizontal scrolling always has a vertical delta -