While循环中的用户输入验证问题



到目前为止,我已经编写了以下代码,它给了我一个错误。

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}。对吗?,

您是否使用调试器运行代码?这个块应该缩进:

if n < 0:
raise ValueError
result[sq] += n

此外,您没有始终如一地将输入转换为lower

我注意到的最后一件事是,在下面的语句中缺少一个逗号:

if b in ['yes' 'y']:

否则你的代码似乎做你所期望的

最新更新