如果未满足两个条件,则拒绝或循环用户输入

时间:2016-10-10 11:02:00

标签: python loops input

我是Python的真正初学者,虽然到目前为止我喜欢它的每一分钟。

我正在制作一个小程序,它接受用户输入,然后用它做任务。我的问题是用户输入的数字必须

(1)所有加起来不超过一个(即a1 + a2 + a3 \ leq 1)

(2)每个单独地< 1。

这是我到目前为止的代码(只是必要的中间位):

 num_array = list()


  a1  = raw_input('Enter percentage a (in decimal form): ')
  a2 = raw_input('Enter percentage b (in decimal form): ')
  ...
  an = raw_input('Enter percentage n (in decimal form): ')


li = [a1, a2, ... , an]

for s in li:
   num_array.append(float(s))

如果他们的输入超出了

的要求,我希望能够建立一些东西来要求用户重新输入内容。

a1 + a2 + a3> 1

或a1> 1,a2> 1,a3> 1等。

我觉得这很容易实现,但由于我的知识有限,我被卡住了!

非常感谢任何帮助: - )

1 个答案:

答案 0 :(得分:4)

input_list = []
input_number = 1
while True:

    input_list.append(raw_input('Enter percentage {} (in decimal form):'.format(input_number))

    if float(input_list[-1]) > 1:     # Last input is larger than one, remove last input and print reason
        input_list.remove(input_list[-1])
        print('The input is larger than one.')
        continue

    total = sum([float(s) for s in input_list])
    if total > 1:    # Total larger than one, remove last input and print reason
        input_list.remove(input_list[-1])
        print('The sum of the percentages is larger than one.')
        continue

    if total == 1:    # if the sum equals one: exit the loop
        break

    input_number += 1