jeudi 18 novembre 2021

Using a for loop for a dictionary based on user input

airport_code = input("Please enter your code")

airport_values = {
    'BCN':'Barcelona',
    'DUB':'Dublin',
    'LIS':'Lisbon',
    'LHR':'London Heathrow',
    'CDG':'Paris',
    'PRG':'Prague',
    'RKV':'Reykjavik',
    'FCO':'Rome'
}

if airport_code in airport_values:
    print('The value is:', airport_values[airport_code])
else:
    print("Sorry that item is not in the list ")

Hi, I have written this code to find whether or not the key the user enters matches with one of the values stored in the dictionary airport_values.

When I then looked at the mark scheme it then uses a for loop instead to iterate through the whole dictionary and makes use of a counter to check each value.

Here is the pseudocode which is written in the mark scheme.

https://i.stack.imgur.com/huUdQ.png

What I'm wondering is how I would then apply this to python instead of the way I have done it.

Any help would be much appreciated.

Aucun commentaire:

Enregistrer un commentaire