【问题标题】:Reject or loop over user input if two conditions not met如果不满足两个条件,则拒绝或循环用户输入
【发布时间】:2017-02-18 18:53:16
【问题描述】:

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

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

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

(2) 每一个都是

到目前为止,这是我的代码(只是必不可少的中间部分):

 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等

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

任何帮助将不胜感激:-)

【问题讨论】:

  • 我看到您需要先读取一个 n ,这是用户将输入的百分比数。之后,您应该重复阅读百分比 n 次(使用 for 语句来实现此目的)。现在,您可以在阅读时添加验证,或在最后添加每个百分比低于 1 的验证。最后,您将添加所有值并验证它们的总和不大于 1。在所有这些代码上永远重复,并且仅在您喜欢时退出,因此如果任何验证失败,您将重新开始。
  • 您可以从wiki.python.org/moin/WhileLoop开始
  • 谢谢@gplayer 和@WalR!这些都是非常有用的建议,感谢您让我思考答案,而不仅仅是给我一个:-)

标签: python loops input


【解决方案1】:
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

【讨论】:

  • 哦,天哪!这正是我想要的,而且很容易理解。感谢您的精彩回答:-)
  • 你还可以做些什么来改进它是设置一定的error 边距(如 10^-3)来捕获浮点错误。那么它将是if (1-error) < total < (1+error):。如果选择 10^-3,总数可能与 1 相差 0.1%,在 10^-5 时,总数可能与 1 相差 0.001%。
  • 这真是太棒了!谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-06-18
  • 2015-06-27
  • 2016-03-18
  • 1970-01-01
  • 2021-09-30
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多