2

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.

3
  • Where is dict 'c'?
    – taurus05
    Commented Feb 4, 2019 at 16:29
  • You can remove the break because using a return already makes you escape the loop, you also do not need to initialize city = '' because you will overwrite it right after with your input.
    – Guimoute
    Commented Feb 4, 2019 at 16:32
  • Hi Guimoute tried what you mentioned still not working Commented Feb 4, 2019 at 16:37

3 Answers 3

1

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.

1

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.

0
1

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()

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.