【发布时间】: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语句。