【问题标题】:Reject user input if criteria not met in Python如果 Python 中不满足条件,则拒绝用户输入
【发布时间】:2016-10-12 15:33:32
【问题描述】:

我知道这个问题与我已经问过的问题相似,但它是一个扩展,因此它自己的空间是合理的:-)

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

1) 总输入加起来为 1

2) 没有大于一的输入。

我已经有了some help with this question,但不得不对其进行一些修改,因为我的代码输入不能很容易地用某个索引“n”分类的输入来编写(提示输入的问题不能真正格式化作为“输入(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”是一个字符串,而不是一个整数,但我想不出一个简单的方法来解决这个问题,或者在这种情况下如何实现对用户输入的循环。

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

感谢您的宝贵时间和帮助!

【问题讨论】:

  • 试试改成float(s)-1
  • 不确定您所说的“很高兴它可以编译”是什么意思:Python 是一种解释型语言
  • @brianpck 好吧,你仍然可以得到SyntaxError,这有点接近 - 它发生在实际解释步骤之前。 The python docs liken the generation of bytecode to compilation.
  • 是什么让你假设"can't easily be written with the inputs being classified by some index "n""?做一个for element in ('hydrogen', 'chlorine', 'calcium'): 是非常好的,并且可以防止诸如s 之类的问题只检查最后一个元素。
  • 看起来您的 continue 语句应该再缩进一级,以符合之前的 if 语句。

标签: python loops input


【解决方案1】:

你只需要在做减法之前强制转换为浮点数:

if float(s) - 1  > 1.0:

这样就可以将s的float值减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

我想这就是你想要的。

【讨论】:

  • 这远不是唯一的问题......看起来缩进已经关闭,因为它的状态 s 只是保留了前一个循环中的最后一个分配值(钙)
  • 感谢@Will 和@brianpck!我知道代码和任何东西一样混乱(我对此很陌生,并且有很多东西要学习!),但是非常感谢您易于理解和启发性的答案!太棒了。
  • 刚刚将它添加到我的代码中,它工作得很好!荣誉和感谢一百万。
【解决方案2】:

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

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:
        a1 = float(a1)
        a2 = float(a2)
        a3 = float(a3)
        break
    except ValueError:
        print('All inputs must be numerals')

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

【讨论】:

  • 谢谢@Jeff_L!这是拒绝非浮点输入的一种非常直接的方法!我喜欢您将我更详尽的担忧简化为这一标准的方式!
【解决方案3】:

您的代码有点混乱。我敢肯定,有人可以在下面挑选漏洞,但试一试,看看它是否有帮助。

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

首先定义问题,然后在循环中处理每个问题,在该循环中,使用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

【讨论】:

  • 哇!谢谢,@Rolf_of_Saxony!这是一段非常好的、易于理解的代码,而且似乎完全符合我的要求!我也很喜欢你如何实现对问题的循环!荣誉。
  • 请注意,如果在输入完成之前答案的总和大于 1,您仍然会遇到问题。在这种情况下,您可能必须清理循环,设置错误标志,以便您可以从头开始。
猜你喜欢
  • 2017-02-18
  • 1970-01-01
  • 2017-10-29
  • 1970-01-01
  • 2019-03-01
  • 1970-01-01
  • 1970-01-01
  • 2023-04-05
  • 1970-01-01
相关资源
最近更新 更多