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

2024-04-24 20:21:56 发布

您现在位置:Python中文网/ 问答频道 /正文

我是一个真正的Python初学者,尽管到目前为止我喜欢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等

我有一种感觉,这将是真的很容易实现,但由于我有限的知识,我卡住了!你知道吗

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


Tags: 用户ingtformana2inputraw
1条回答
网友
1楼 · 发布于 2024-04-24 20:21:56
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

相关问题 更多 >