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}

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

下面是一个完整的实现,我将展示如何"表驱动"这类事情。我的意思是,核心代码是基于脚本顶部声明的列表。您可以从这个脚本中添加(或删除)元素,而不必更改主代码。输入提示与你的有很大的不同,但我相信你会明白的。

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}')

相关内容

  • 没有找到相关文章

最新更新