Finn Geraghty
Finn Geraghty

Reputation: 39

elif statement not working as expected

I'm trying to look through multiple sources to see which one has a specific entry.

My input looks like:

json_str2 = urllib2.urlopen(URL2).read()
u = json.loads(json_str2)
#load all five results
One = u['flightStatuses'][0]
Two = u['flightStatuses'][1]
Three = u['flightStatuses'][2]
Four = u['flightStatuses'][3]
Five = u['flightStatuses'][4]

My if statement works correctly and I get the correct result:

if One['flightNumber'] == str(FlEnd):
    fnumber = One['flightId']
    print fnumber

But when I add the elif: the answer is wrong (nothing) even when the first statement is True.

I don't understand why the elif doesn't work?

# if statement checks each result to define flightId, needed for tracking.
if One['flightNumber'] == str(FlEnd):
    fnumber = One['flightId']
elif Two['flightNumber'] == str(FlEnd):
    fnumber = Two['flightId']
print fnumber

Upvotes: 0

Views: 125

Answers (1)

kindall
kindall

Reputation: 184201

You should write this as a loop over the five flight statuses instead of using five variables and five conditions.

results = json.loads(urllib2.urlopen(URL2).read())['flightStstuses']
for result in results:
    if result['flightNumber'] == str(FlEnd):
        fnumber = result['flightId']
        break
else:
    fnumber = None
print fnumber

Upvotes: 3

Related Questions