【问题标题】:Having problems using dictionaries keys and values within a while loop conditions在 while 循环条件下使用字典键和值时遇到问题
【发布时间】:2023-01-01 19:15:05
【问题描述】:

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

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


    【解决方案1】:

    在提出问题时,我意识到我可以将所有键作为一个列表,将所有值作为另一个列表并在循环中使用它们。这现在有效,我只需要找到一种方法来阻止它无限地继续下去:

    name = input(f"Hello, what's your name? ") 
    age = int(input(f"And what is your age, {check()}? "))
    
    prices_dict = {3: 'free', 11: 10, 12: 15}
    
    age_ranges = list(prices_dict.keys())
    prices = list(prices_dict.values())
    
    while True:
        if age < age_ranges[0]:
            print(f"Your ticket is {prices[0]}!")
        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]}")
    

    总是乐于接受新的、更好的方法来解决这个问题

    【讨论】:

    • 只是删除循环?
    猜你喜欢
    • 2017-06-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多