我知道这个问题和我已经问过的问题很相似,但它是一个扩展,因此它有自己的空间
我是一个Python新手,编写一个代码,它从用户那里获取输入,然后将用户输入存储在数组中(以后再做更多的工作),前提是满足两个条件:
1)总输入加起来为1
2)没有输入本身大于1。在
我已经有了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不喜欢这行代码
^{pr2}$
它会抛出错误:TypeError: unsupported operand type(s) for -: 'str' and 'int'
我知道这是因为“s”是一个字符串,而不是一个整数,但是我想不出一个简单的方法来解决这个问题,或者在这种情况下如何实现对用户输入的循环。在
如何改进此程序,使其仅在满足条件时将用户输入写入数组?在
谢谢你的时间和帮助!在