python-3.xdictionarykeyreturn-valueonchange

change value in dictionary in python


In the code below, I changed the value and it changed in the same block, but when the loop repeats again, the changes are not applied at the beginning of the loop.

while True:    
    airplane_ticket = {'Berlin':'','price':'$700', 'available':5}   
    print(airplane_ticket)  
    name_ticket = input('please enter the name of city you want to reserved its ticket: ')  
    if name_ticket == 'Berlin':
        number = int(input('How many ticket you need: '))    
        airplane_ticket['available'] -= number

Solution

  • You are setting the value of airplane_ticket to be {'Berlin':'','price':'$700', 'available':5} at the start of every loop, so no matter what you set it to afterwards it will always be overwritten.

    Bringing the initialisation statement for airplane_ticket outside the while True: loop should fix this.

    airplane_ticket = {'Berlin':'','price':'$700', 'available':5}   
    while True:
        print(airplane_ticket)  
        name_ticket = input('please enter the name of city you want to reserved its ticket: ')  
        if name_ticket == 'Berlin':
            number = int(input('How many ticket you need: '))    
            airplane_ticket['available'] -= number