Reputation: 11
I have a program that will get a users number, find all the prime numbers up to that point and store them in a list, now i need from that list to see if two of them together adds to the user input, this is where i cant seem to get it right. I'll just put the last bits in that i need help with.
num = int(raw_input('enter a number: '))
b = [2, 3, 5, 7, 11, #... etc up to the prime before the users number]
for a in b:
for c in b:
if c + a = num
print num, '=', a, '+', c
break
However when i have a user input of say 8, it prints out:
8=3+5
8=5+3
how can i get it to only print one value?
Upvotes: 1
Views: 342
Reputation: 40394
Alternatively, you can move the loops to a function and use return
inside that function to exit from both loops:
def print_first(b):
for a in b:
for c in b:
if c + a == num:
print num, '=', a, '+', c
return
num = int(raw_input('enter a number: '))
b = [2, 3, 5, 7, 11, #... etc up to the prime before the users number]
print_first(b) # 8 = 3 + 5
Upvotes: 1
Reputation: 14081
You're only breaking out of the inner loop, not the outer one.
num = int(raw_input('enter a number: '))
b = [2, 3, 5, 7, 11]
for a in b:
for c in b:
if c + a == num:
print num, '=', a, '+', c
break
else:
continue
break
output:
$ python ~/tmp/soprim.py
enter a number: 8
8 = 3 + 5
For-else in python is a little counter-intuitive; else only executes if the loop completed without breaking. So in this case, if it never hits the first break, the else clause runs and it continues with the next outer loop execution. But it you hit the first break, else doesn't run, so you hit the second break, and then you're out of both loops.
Upvotes: 4