如何使用字典创建条件?

2024-06-14 07:43:03 发布

您现在位置:Python中文网/ 问答频道 /正文

抱歉,如果这听起来很简单,但我是新的Python。你知道吗

如果一个孩子的分数大于或等于100,他们应该得到8份礼物;如果一个孩子的分数在50到100之间,他们得到5份礼物;如果一个孩子的分数低于50,那么他们得到2份礼物。你知道吗

如何使用词典检查用户的输入是否正确?你知道吗

它将首先显示他们的分数,如:

presents=[]
People={"Dan":22,
        "Matt":54,
        "Harry":78,
        "Bob":91}

def displayMenu():
    print("1. Add presents")
    print("2. Quit")
    choice = int(input("Enter your choice : "))
    while 2< choice or choice< 1:
        choice = int(input("Invalid. Re-enter your choice: "))
    return choice

def addpresents():
    name= input('Enter child for their score: ')
    if name == "matt".title():
        print(People["Matt"])
    if name == "dan".title():
        print(People["Dan"])
    if name == "harry".title():
        print(People["Harry"])
    if name == "bob".title():
        print(People["Bob"])
    present=input('Enter number of presents you would like to add: ')
    if present
        #This is where I got stuck

option = displayMenu()

while option != 3:
    if option == 1:
       addpresents()
    elif option == 2:
        print("Program terminating")

option = displayMenu()

Tags: nameinputiftitle孩子people分数option
1条回答
网友
1楼 · 发布于 2024-06-14 07:43:03

与所问问题相关:

If a child's score is greater or equal than 100 they should get 8 presents; if a child's score is between 50 and 100 they get 5 presents while if a child's score is below 50 then they get 2 presents.

创建一个字典,其中键是分数的布尔条件。但是字典每次都必须重新创建,因为它的键中使用了score,而且每个循环的分数可能不同。你知道吗

>>> score = 3
>>> presents = {score < 50: 2,
...             50 <= score < 100: 5,
...             score >= 100: 8
...             }[True]
>>> presents
2
>>> # and keep re-doing the 3 statements for each score.

实际上,每个字典键都变成TrueFalse,其中只有一个值是True。因此,获取True的值给出礼物的数量。你知道吗

将其应用到函数中更有意义,比如:

def get_presents(score):
    return {score < 50: 2,
            50 <= score < 100: 5,
            score >= 100: 8
            }[True]

像这样使用:

>>> get_presents(25)
2
>>> get_presents(50)
5
>>> get_presents(100)
8
>>>

至于您使用的代码,这似乎与问题的意图相去甚远。你知道吗

或者,您可以使用int(score/50)作为键:

>>> present_dict = {1: 2,
...                 2: 5,
...                 3: 8
...                 }
>>>
>>> score = 500
>>> present_dict[min(int(score / 50) + 1, 3)]  # needed to not go over 3
8
>>> score = 25
>>> present_dict[min(int(score / 50) + 1, 3)]  # the +1 needed since it's int div
2
>>> # or put the expression above in the `get_presents` function and return that

相关问题 更多 >