Posteingang
Posteingang

Reputation: 53

I need advice on this 'else' block

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.

Upvotes: 0

Views: 38

Answers (1)

bereal
bereal

Reputation: 34281

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")

Upvotes: 1

Related Questions