【问题标题】:take input until the condition is completed in python接受输入直到条件在python中完成
【发布时间】:2020-10-01 08:42:32
【问题描述】:

我想接受两个输入。程序必须只接受有效分数(分数必须在 [0 到 10] 范围内)。每个分数必须单独验证。如果输入无效,我想打印“错误输入”。 在接受两个有效输入后,我想打印这些值的总和。

count = 0
count2 = 0
while True:
    a = float(input())
    if 0 <= a <= 10:
        count2 += a
        count2 += 1
    b = float(input())
    if 0 <= b <= 10:
        count2 += b
        count += 1
    else:
        print('Wrong input')
    if count == 2:
        break

print('Sum = {}'.format(count2))

示例输入:

-3.5

3.5

11.0

10.0

输出:

输入错误

输入错误

总和 = 13.5

【问题讨论】:

    标签: python-3.x input while-loop conditional-statements


    【解决方案1】:

    通过使用两个 while 循环,您可以轻松地单独验证每个输入,直到获得预期值。

    while True:
        a = float(input())
        if 0<=a<=10:
            break
        else:
            print('Wrong Input')
    
    while True:
        b = float(input())
        if 0<=b<=10:
            break
        else:
            print('Wrong Input')
    print("sum =", a+b)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-01-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-04-10
      • 1970-01-01
      相关资源
      最近更新 更多