How to fix a problem with input() in python?

Question:

I’m creating my first program on python. The objective is to get an output of trip cost. In the below code I want python to throw an error and ask user to retry if the input is not a part of the dictionary.

I tried using while True but when I use the code it does makes me retry on a wrong input but does not throw an error intimating the user.

c = {"Charlotte": 183, "Tampa": 220, "Pittsburgh": 222, "Los Angeles": 47}

def plane_ride_cost():
    city = ''
    while True:
        city = input("Name of the city: ")
        if  city in c.keys():
            return c[city]
            break
    else:
        print ("Invalid input please try again")

plane_ride_cost()

Output:
Name of the city: Hyderabad
Name of the city: 

if you notice it takes the entry and then asks me to retry without the intimation.

Asked By: ragethewolf

||

Answers:

So, I copied your code and ran it. The only problem with it was that indent, so basically I corrected that:

 c = {"Charlotte": 183, "Tampa": 220, "Pittsburgh": 222, "Los Angeles": 47}
 def plane_ride_cost():
     city = ''
     while True:
         city = input("Name of the city: ")
         if  city in c.keys():
             return c[city]
             break
         else:
             print ("Invalid input please try again")

plane_ride_cost()

When running that, if you type in “Arizona”, for example, it returns “Invalid input please try again”, and if you input the names in the dictionary, it returns the dictionary value.

Explanation:

Python uses indentation to structure the code. In your example, else is aligned with while, so it is part of the while statement, and is executed upon normally exiting while loop (not with break).

You want the else to be aligned with if, so that it will be executed every time through the loop, if the if condition (city in c.keys()) is not True.

Answered By: marcogemaque

You can also do that with tail recursion.

c = {"Charlotte": 183, "Tampa": 220, "Pittsburgh": 222, "Los Angeles": 47}

def plane_ride_cost():
    city = input("Name of the city: ")
    if city in c:     #try:
        return c[city]
                      #except:
    print ("Invalid input please try again")
    plane_ride_cost()

plane_ride_cost()
Answered By: b m gevariya

Another solution, in the spirit of easier to ask for forgiveness than permission:

def plane_ride_cost():
    while True:
        city = input("Name of the city: ")
        try:
            return c[city]
            break
        except KeyError:
            print ("Invalid input please try again")

plane_ride_cost()

try block attempts to just execute the line(s), without checking if the input is correct.

If it works, except block is skipped.

If there is a KeyError, which happens if the key city doesn’t exist in c, it will be caught by except block. Instead of the program crashing, the line(s) in the except block are executed.

You can have multiple `except blocks, to catch different exceptions.

Answered By: Granny Aching
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.