Having problems using dictionaries keys and values within a while loop conditions

Question:

I want to create a little program that after obtaining the user’s age it will tell them the relative cost for a movie ticket for the age range they fall within. This is easy to do with a few age ranges, but I just wanted to train a bit and work with dictionaries. So I made the following code, with the idea that in the future maybe I will change idea about the ranges and will only have to change within the dictionary and not everywhere in the code.

name = input(f"Hello, what's your name? ")
age = int(input(f"And what is your age, {name}? "))

prices = {3: 'free', 11: 10, 12: 15}

# print(prices[0])

while True:
    if age < prices{0}
        print(f"Your ticket is free!")
    elif prices{0} <= age < prices{1}:
        print(f"The price of your ticket is {int{} ")
    else:
        print(f"The price of your ticket is")

I know this is not the way, I have tried calling keys and values even with for loops, using them directly in the if… Can someone help me understand how to make conditions work in checking dictionary keys?

Asked By: spool

||

Answers:

Whilst making the question I realized I could take all the keys as a list, and all the values as another list and use these in the loop. This now works, I defined it within a function to be sure to be able to use it as many times as I want, I will just add a condition for when the user wants to stop to make it stop.

def get_ticket_price():
    name = input(f"nHello, what's your name? ")
    age = int(input(f"nAnd what is your age, {name.title()}? "))

    prices_dict = {3: 'free', 11: 10, 12: 15}

    age_ranges = list(prices_dict.keys())
    prices = list(prices_dict.values())

    found = False

    while not found:
        if age < age_ranges[0]:
            print(f"nYour ticket is {prices[0]}! Next customer, please.")
            found = True
        elif age_ranges[0] <= age < age_ranges[1]:
            print(f"nThe price of your ticket is ${prices[1]}. Next customer, please.")
            found = True
        else:
            print(f"nThe price of your ticket is ${prices[2]}. Next customer, please.")
            found = True

while True:
    get_ticket_price()

Always open to new, better ways to work this out

Answered By: spool

You have to ask for the age in the while loop, and exit for a particular value.

prices_dict = {3: 0, 11: 10, 12: 15}

age_ranges = list(prices_dict.keys())
prices = list(prices_dict.values())
while True:
    name = input(f"Hello, what's your name? ") 
    age = int(input(f"And what is your age, {name}? "))
    if age < age_ranges[0]:
        print(f"Your ticket is free!")
    elif age_ranges[0] <= age < age_ranges[1]:
        print(f"The price of your ticket is {prices[1]}")
    else:
        print(f"The price of your ticket is {prices[2]}")
    answer = input("Do you with to continue? (Type 'no' to exit)")
    if answer == "no":
        break
Answered By: MercifulSory

Why use dictionary in this case at all? since you are using if statement, just define your ranges in that is statement like you tried already, just with actual values.

If age < 3:
    print("ticket free")
elif age < 10:
    print("price of your ticket is x")

etc. only thing i would suggest with this approach is to consider if the prices my change in the future, if they can, then i would create a dictionary that would have prices corresponding to the if statement options so its easier to change in the future. something like this:

prices = {3:0,10:"x"}


print("price of your ticket is {}".format(prices[10])
Answered By: Gregory Sky

While this is not the most efficient solution for large problems, as it takes linear time, it is good to show some new things.
Optimally you can do it with log n in a binary search lookup. For that you can use your two lists and a index value.

You can put ranges in dictionaries. Remember that range objects exclude the last value and to be sure there is no gap


age = int(input(f"And what is your age, {check()}? "))
prices = { range(0, 4) : "free", 
           range(4, 12) : 10, 
           range(12, 999) : 15 
          }

for age_range, price in prices.items():
   if age in age_range:
      print(f"nYour ticket is {price}! Next customer, please.")
      found=True
      break
else: # This will activate if no break statement happend in the loop
   print(f"n{age} is not a valid age in our cinema.")
   found=False
Answered By: Daraan

Iterate dictionary key with for loop, break and get the value of key if age is in range of the key + 1 else get the value of last key. You can add more key value to the dict without necessarily changing the code:

prices = {3: 'free', 11: 10, 12: 15}

name = input(f"Hello, what's your name? ")
age = int(input(f"And what is your age, {name}? "))

for i in prices:
    if age in range(i+1):
        ticket = prices[i]
        break
    ticket = prices[i]

print(f"Your ticket is {ticket}!")

But it’ll be better with while and try except:

prices = {3: 'free', 11: 10, 12: 15}

name = input(f"Hello, what's your name? ")

while True:
    try:
        age = int(input(f"And what is your age, {name}? "))
        for i in prices:
            if age in range(i+1):
                ticket = prices[i]
                break
            ticket = prices[i]
        break
    except ValueError:
        print('Invalid Age')

print(f"Your ticket is {ticket}!")

Output:

Hello, what's your name? Adam
And what is your age, Adam? 17
Your ticket is 15!

Hello, what's your name? Eva
And what is your age, Eva? 12
Your ticket is 15!

Hello, what's your name? Cain
And what is your age, Cain? 9
Your ticket is 10!

Hello, what's your name? Abel
And what is your age, Abel? 2
Your ticket is free!
Answered By: Arifa Chan
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.