首页 > 解决方案 > Python根据用户在字典中的输入将值相加

问题描述

根据我的字典,根据用户的输入,我最终如何获得值的总和?字典中的所有值都从 0 开始,然后根据用户对问题的输入响应而变化。我必须包含以下代码:

my_dictionary = {"Dog": 0, "Cat": 0, "Brother": 0, "Sister": 0, "Daughter": 0, "Son": 0}

yes_response = ["yes", "y"]
no_response = ["no", "n"]

我希望根据用户的响应添加字典中的值。如何编写输出代码如下:

Do you have any pet(s)? Please enter Y/N: yes
You do have pet(s), that correct? Please enter Y/N: yes
How many dog(s) do you have? Please enter an integer: 2
You have 2 dog(s), is that correct? Please enter Y/N: Y
How many cat(s) do you have? Please enter an integer: 3
You have 3 cat(s), is that correct? Please enter Y/N: abcdefghhijklmnop
Sorry, your input "abcdefghhijklmnop" is invalid. Please try again.
You have 3 cat(s), is that correct. Please enter Y/N: Y

    
Do you have any siblings? Please enter Y/N: yes
You do have siblings, is that correct? Please enter Y/N: yes
How many sister(s) do you have? Please enter an integer: 1
You have 1 sister(s), is that correct? Please enter Y/N: Y
How many brother(s) do you have? Please enter an integer: None
Sorry, your input "None" is invalid. Please try again.
How many brother(s) do you have? Please enter an integer: 2
You have 2 brother(s), is that correct? Please enter Y/N: N
How many brother(s) do you have? Please enter an integer: 0
You have 0 brother(s), is that correct? Please enter Y/N: Y
    
Do you have any children? Please enter Y/N: 123456789
Sorry, incorrect response. Please try again.
Do you have any children? Please enter Y/N: no
You do not have any children, is that correct? Please enter Y/N: yes
    
Based on your valid input from the questions above, your dictionary is:  
{"Dog": 2, "Cat": 3, "Brother": 0, "Sister": 1, "Daughter": 0, "Son": 0}

我怎样才能得到像上面这样的结果,根据用户的正确答案计算有多少狗、猫、兄弟、姐妹等作为字典中的值?

标签: pythonpython-3.xdictionaryinputwhile-loop

解决方案


这是我展示的完整实现,以演示如何“表驱动”这种事情。我的意思是核心代码基于脚本顶部声明的列表。您可以从此脚本中添加(或删除)元素,而无需更改主代码。输入提示与您的不同,但我相信您会明白的。

questions = [['pets', ['Dog', 'Cat']],
             ['siblings', ['Brother', 'Sister']],
             ['children', ['Son', 'Daughter']]]
result = {x: 0 for y in questions for x in y[1]}
for q in questions:
    while True:
        a = input(f'Do you have any {q[0]}? ').lower()
        if a in ['no', 'n']:
            break
        if a not in ['yes', 'y']:
            continue
        for sq in q[1]:
            while True:
                a = input(f'How many {sq}s do you have? ')
                try:
                    n = int(a)
                    if n < 0:
                        raise ValueError
                    result[sq] += n
                    break
                except ValueError:
                    print('Please only respond with positive numbers')
        break
for k, v in result.items():
    s = '' if v == 1 else 's'
    print(f'You have {v} {k}{s}')

推荐阅读