【发布时间】:2021-10-14 13:27:13
【问题描述】:
到目前为止,我编写了以下代码,但它给了我一个错误。
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']:
b = input(F"You answered no. Is that correct?")
if b in ['yes' 'y']:
break
if a not in ['yes', 'y']:
b = input(F"You answered no. Is that correct?")
continue
else:
b = input(F"You answered yes, is that correct?")
for sq in q[1]:
while True:
a = input(f'How many {sq}s do you have? ')
try:
b = input(F"You answered that {a}. Is that correct?")
if b = ["yes", "y"]:
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}')
我希望我的代码运行如下:
Do you have any pets? Yes
You answered "Yes". Is that correct? Yes
How many dogs do you have? 2
You answered "2". Is that correct? Yes
How many cats do you have? 0
You answered "0". Is that correct Yes
Do you have any siblings? Yes
How many brother do you have? 1
You answered "1". Is that correct? Yes
How many sister do you have? 0
You answered "0". Is that correct? Yes
Do you have any children? No
You answered "No". Is that correct? Yes
Based on your response above, you have:
2 dogs,
0 cats,
1 brother,
0 sister,
0 children.
我不确定如何将下面的确认问题输入放在我的 while 循环中,正如我在上面写的那样。
“您输入了 {user_input}。正确吗?”
【问题讨论】:
-
您可能想用
questions制作字典并循环遍历它
标签: python python-3.x for-loop input while-loop