如果在Python中未满足条件,则拒绝用户输入

时间:2016-10-12 15:33:33

标签: python loops input

我知道这个问题类似于我已经问过的问题,但它是一个扩展,并且证明了它自己的空间: - )

我是一个Python新手,编写一个代码,该代码从用户那里获取输入,然后将该用户输入存储在一个数组中(以便稍后执行更多操作),前提是满足两个条件:

1)总投入总计为一个

2)没有输入本身大于一个。

我已经有了some help with this question,但由于我的代码输入无法轻易编写,输入被某些索引" n" (提示输入的问题实际上不能格式化为" input(n),其中n从1到A")

到目前为止,这是我的尝试:

num_array = list()
input_number = 1
while True:

     a1  = raw_input('Enter concentration of hydrogen (in decimal form): ')
     a2 = raw_input('Enter concentration of chlorine (in decimal form): ')
     a3 = raw_input('Enter concentration of calcium (in decimal form): ')



     li = [a1, a2, a3]

     for s in li:
        num_array.append(float(s))
        total = sum([float(s)])

     if float(s-1)  > 1.0:     
         num_array.remove(float(s-1))
         print('The input is larger than one.')

     continue


     if total > 1.0:    # Total larger than one, remove last input and print reason
         num_array.remove(float(s-1))
         print('The sum of the percentages is larger than one.')

     continue

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

input_number += 1

我很高兴它编译,但Python不喜欢这行

if float(s-1)  > 1.0: 

它会抛出错误:

TypeError: unsupported operand type(s) for -: 'str' and 'int'

我知道这是因为" s"是一个字符串,而不是整数,但我不能想到解决问题的简单方法,或者在这种情况下如何在用户输入上实现循环。

如果满足条件,如何改进此程序只将用户输入写入数组?

感谢您的时间和帮助!

3 个答案:

答案 0 :(得分:2)

在进行减法之前,您只需要转换为浮动:

if float(s) - 1  > 1.0:

这样,您可以从s

的浮点值中减去1

编辑:我还会对您的代码进行以下更改,以便更正确地运行。

num_array = list()
input_number = 1
while True:
    a1  = raw_input('Enter concentration of hydrogen (in decimal form): ')
    a2 = raw_input('Enter concentration of chlorine (in decimal form): ')
    a3 = raw_input('Enter concentration of calcium (in decimal form): ')

    try:   # try to cast everythiong as float.  If Exception, start loop over.
        li = [float(a1), float(a2), float(a3)]
    except ValueError:
        continue

    total = 0  # reset total to 0 each iteration
    for s in li:
        num_array.append(s)
        total += s  # use += to keep running toatal

        if s > 1.0:     
            num_array.remove(s)
            print('The input is larger than one.')
            break  # break rather than continue to break out of for loop and start while loop over


        if total > 1.0:
            num_array.remove(s)
            print('The sum of the percentages is larger than one.')
            break   # break again

    if total == 1.0:
        break

我认为这就是你想要的。

答案 1 :(得分:2)

您可以确保输入类型的一种方法是使用try / except条件退出循环:

    let line = CAShapeLayer()
    let linePath = UIBezierPath()
    linePath.move(to: CGPoint(x: 100, y: 100))
    linePath.addLine(to: CGPoint(x: 300, y: 300))
    line.path = linePath.cgPath
    line.strokeColor = UIColor.red.cgColor
    self.view.layer.addSublayer(line)

然后,如果他们没有输入Python可以转换为浮点数的东西,它就会停留在循环中。

答案 2 :(得分:1)

您的代码有点混乱。我确信有人可以在下面挑一些洞,但是给它一个旋转,看看它是否有帮助。

最初将问题放入列表中,允许您在单个循环中一次询问和验证输入,只有在询问,验证和存储所有问题后才退出循环。

首先定义问题,然后在循环内和循环内处理每个问题,使用while语句保持相同的问题,直到提供了有效的答案。

input_number = 1
questions = []
answers = []
questions.append('Enter concentration of hydrogen (in decimal form): ')
questions.append('Enter concentration of chlorine (in decimal form): ')
questions.append('Enter concentration of calcium (in decimal form): ')
for i in questions:
    while True:
        try:
            ans  = float(raw_input(i)) #Accept the answer to each question
        except ValueError:
            print('Please input in decimal form')
            continue # Invalid input, try again
        if ans > 1.0:
            print('The input is larger than one.')            
            continue # Invalid input, try again
        if sum(answers,ans) > 1.0:
            print('The sum of the answers is larger than one.')
            print(answers)
            continue # Invalid input, try again
        answers.append(ans)
        break # The answer to this question has been validated, add it to the list
print ("Your validated input is ",answers)
input_number += 1