我是一个真正的 Python 初学者,尽管到目前为止我很喜欢它的每一分钟。
我正在制作一个小程序,它接受用户输入,然后用它来做一些事情。我的问题是用户输入的数字必须
(1) 所有加起来不超过 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 等。
我有一种感觉,这真的很容易实现,但由于我的知识有限,我被困住了!
任何帮助将非常感激 :-)
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
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)