breaking a while loop | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 2

breaking a while loop

Hello I did not post in a while (not pun intended). I am doing a course on Udemy now. One of the section had a list of problem to solve. One is to do a python code that give you a succession of prime number until you tell it to stop. Calculating prime number and putting them on a list is not complicated, but I am not able to make code stop. Lp = [] def prime(n): l = range(2,n) f = 0 while f == 0: for x in l: if n%x == 0: n += 1 prime(n) else: Lp.append(n) print(f" {n} is prime") if input('type y for one more prime ') == 'y': n += 1 prime(n) else: print(f"The prime found in this session are {Lp}") f = 1 prime(5) I tried different technic ( especially the "break" function) . But nothing that's work. The code print me the list as soon as you put another imput than 'y' but kept asking if you want a new prime.. What I am missing here ? ps : I know that break work only with if statement, but various variation did not worked either.

14th Jan 2020, 1:43 PM
nicolas seespan
nicolas seespan - avatar
3 Answers
+ 3
I’m not sure whether it would be considered “good practice” but the simplest way I can think of to deal with this problem is to use return instead of break. Break was stopping the for loop instead of the while loop where you presumably had it
14th Jan 2020, 1:57 PM
Jax
Jax - avatar
+ 1
Do they want you to stop the output interactively? Because with pure console code that doesn't look like a plausible solution. Do they maybe just want you to allow an upper limit to be set? If you are allowed to confirm between every number, it's more simple. You might do it for example like this (return for next number, 'stop' for end: from math import sqrt def primes(): yield 2 n = 3 while True: prime = True for div in range(3, int(sqrt(n))+1): if not n%div: prime = False break if prime: yield n n += 2 for p in primes(): print(p, end=' ') inp = input() if inp=='stop': break
14th Jan 2020, 3:03 PM
HonFu
HonFu - avatar
0
So after some more "experimenting" I had failure, failure, failures. I decided to go for a more modular solution and I did function : #programme has to keep finding prime number until user say no nomre Lp = [] def prime(n): l = range(2,n) v = True for x in l: if n%x == 0: v = False break if v == True: return n def lol(g): c = len(Lp) + 1 while len(Lp) < c: b = prime(g) if b != None: Lp.append(b) g +=1 print(f"the first {len(Lp)} prime number are {Lp}") def loo(g): while len(Lp) < d: b = prime(g) if b != None: Lp.append(b) g +=1 print(f"the first {len(Lp)} prime number are {Lp}") d = int(input('How many prime number do you want\n')) loo(2) u = 'y' while u == 'y': u = input('Type y for one more prime\n') if u == 'y': lol(Lp[-1]+1)
15th Jan 2020, 7:26 AM
nicolas seespan
nicolas seespan - avatar