【发布时间】:2021-10-13 16:14:46
【问题描述】:
根据我的字典,如何根据用户的输入最终获得值的总和?字典中的所有值都从 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}
如何根据用户的正确答案获得像上面那样计算有多少狗、猫、兄弟、姐妹等作为字典中的值的结果?
【问题讨论】:
-
您可以使用 defaultdict 并随时增加价值
标签: python python-3.x dictionary input while-loop