【问题标题】:User Input Verification Question in While LoopWhile循环中的用户输入验证问题
【发布时间】: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


【解决方案1】:

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

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

除了您没有始终将输入转换为lower

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

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

否则您的代码似乎会按照您的预期进行

【讨论】:

    猜你喜欢
    • 2016-03-08
    • 2020-07-07
    • 2021-05-13
    • 2016-05-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-05
    相关资源
    最近更新 更多