在 while 循环条件下使用字典键和值时出现问题

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

提问人: 提问时间:1/1/2023 最后编辑:shafee 更新时间:1/2/2023 访问量:99

问:

我想创建一个小程序,在获得用户的年龄后,它会告诉他们他们所属年龄范围内的电影票的相对成本。这在几个年龄段很容易做到,但我只是想训练一下并使用词典。因此,我编写了以下代码,其想法是,将来也许我会改变关于范围的想法,并且只需要在字典中更改,而不是在代码中的任何地方更改。

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

我知道这不是办法,我尝试过调用键和值,甚至使用 for 循环,直接在 if 中使用它们......有人可以帮我了解如何使条件在检查字典键时起作用吗?

Python 字典 切片

评论

0赞 Daraan 1/1/2023
词典按方括号中的键编制索引,例如 或。prices[3] -> 'free'prices[11] -> '10'
0赞 Daraan 1/1/2023
问题是对于您不能真正使用字典的范围(期望您为每个可能的年龄添加一个键)。最简单但效率最低的方法是做出(很多)if语句 - 就像你在回答中所做的那样。但是,对于许多选择来说,这些可能会变得混乱。最后,这个问题需要更多的树状结构。
0赞 Pythoneer 1/1/2023
你的语法很有问题。我不能在不知道在字符串中放什么的情况下复制和粘贴它f'

答:

0赞 user18377332 1/1/2023 #1

在提出问题时,我意识到我可以将所有键作为一个列表,将所有值作为另一个列表并在循环中使用它们。这现在可以工作了,我在函数中定义了它,以确保能够根据需要多次使用它,我只会添加一个条件,当用户想要停止时,它会停止。

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

始终对新的、更好的方法来解决这个问题持开放态度

0赞 MercifulSory 1/1/2023 #2

您必须在 while 循环中询问年龄,然后退出特定值。

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
0赞 Gregory Sky 1/1/2023 #3

在这种情况下为什么要使用字典?由于您使用的是 if 语句,因此只需像您已经尝试过的那样在 is 语句中定义范围,只需使用实际值即可。

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

对于这种方法,我唯一建议的是考虑将来的价格是否发生变化,如果可以的话,那么我将创建一个字典,其中包含与 if 语句选项相对应的价格,以便将来更容易更改。像这样的东西:

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


print("price of your ticket is {}".format(prices[10])
0赞 Daraan 1/1/2023 #4

虽然这不是解决大问题最有效的解决方案,因为它需要线性时间,但展示一些新事物是件好事。理想情况下,您可以在二进制搜索查找中使用 log n 来做到这一点。为此,您可以使用两个列表和一个索引值。

您可以将范围放入字典中。请记住,对象排除最后一个值,并确保没有间隙range


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

评论

0赞 1/2/2023
该死的,这看起来很酷!还有一些简单的东西。谢谢
0赞 Arifa Chan 1/1/2023 #5

使用 for 循环迭代字典键,如果 age 在键 + 1 的范围内,则 break 并获取键的值,否则获取最后一个键的值。您可以向字典添加更多键值,而不必更改代码:

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}!")

但是它会更好,并尝试以下情况:

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}!")

输出:

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!