0

Why does the else statement get printed here?

for elem in data:
    if choose_id == elem['id']:
        print(f"{elem['ip']} : {elem['id']}")
else:
    print("No ID found")

output is:

ID to search > 6
10.xx.xxx.xx : 6
10.xx.xxx.xx : 6
10.xx.xxx.xx : 6
10.xx.xxx.xx : 6
No ID found

I've tried putting in a 'break' statement in the if block but it only iterates once.

I'd appreciate some advice.

Posteingang
  • 53
  • 1
  • 8
  • 3
    Else gets printed because it's not indented - it's for/else, not if/else. – h4z3 Dec 03 '19 at 13:47
  • 3
    In `for ... else` statement `else` part runs if the loop ends without `break`, so that's exactly what happens here. – bereal Dec 03 '19 at 13:48
  • @h4z3 I initally had it indented but it just prints 'no id found' for every element – Posteingang Dec 03 '19 at 14:20
  • @bereal where should the `break` go? – Posteingang Dec 03 '19 at 14:25
  • @Posteingang in your case `break` won't help, because you want to iterate to the end. I think, you'll need a variable `found = False` which is set to `True` once you have a match, and in the end print the message if there's no match. – bereal Dec 03 '19 at 14:32

1 Answers1

1

In your case the for..else statement won't help, because you want to iterate through the entire list in any case, and the else part will run after than. I think, the simplest way is to have a found variable, like this:

found = False
for elem in data:
    if choose_id == elem['id']:
        found = True
        print(f"{elem['ip']} : {elem['id']}")

if not found:
    print("No ID found")
bereal
  • 32,519
  • 6
  • 58
  • 104
  • how do you know they want to iterate to the end of the list? maybe they can break after one `if` clause is met sucesfully – Chris_Rands Dec 03 '19 at 14:37
  • @Chris_Rands I understood that from the statement _I've tried putting in a 'break' statement in the if block but it only iterates once._, and the fact that the id seems to be non-unique in their output. – bereal Dec 03 '19 at 14:40
  • This worked. I never would have thought to use `found = True/False`. Glad this got re-opened, many thanks. – Posteingang Dec 03 '19 at 14:43