Search code examples
pythonkeyerror

Stuck at "if" and it wont continue past it


I'm currently stuck at line 22, if I input 15 km instead of 15 miles it won't continue towards the elif statement which is ment to convert 15 km into miles.

I have tried switching key & values, and been trying to figure out how the code works logically.

distance = {}
km_miles = input("Type distasnce and unit (miles or km)\n>>>")
value, key = km_miles.split(" ")
distance[key] = float(value)

if distance[key] == distance['miles']:
    print("Printing from miles to kilometers")
    print(miles_to_km(distance[key]))

elif distance[key] == distance['km']:
    print("Printing from kilometers to miles")
    print(km_to_miles(distance[key]))

else:
print("try again")

What I'm expecting it to do is that if I type 15 km, its meant to enter the elif distance[key] == distance['km'] and not just fail at line 22.

if I didn't type either miles or km. Then I would expect it to print out "try again".


Solution

  • You're definitely lost with logic flow here. To debug your issue, try printing distance variable before if/else statement, you'll see what's wrong with it.

    If you need to check the units, just do

    value, unit = km_miles.split(" ")
    if unit == 'miles':
        ...
    elif unit == 'km':
        ...