从输入的数组中减去数字

时间:2013-05-07 16:08:19

标签: python subtraction

我是Python的新手,并试图找出如何减去用户输入的数组中的数字。例如,在我的程序的早期,我有: `

peakone = raw_input("Where is the next large peak?: ")
next_peak.append(peakone)
peaktwo = raw_input("Where is the next large peak?: ")
next_peak.append(peaktwo)

现在我想从peaktwo中减去peakone并将此值保存为第三个。如果有的话,最好的方法是什么?

2 个答案:

答案 0 :(得分:0)

你可以这样做:

peakthree = float(peaktwo) - float(peakone)

您从raw_input获得的是一个字符串,因此您需要将其转换为数字类型,例如floatint。考虑编写这样的代码:

def get_next_peak():
    return float(raw_input("Where is the next large peak?: "))

next_peak = []
next_peak.append(get_next_peak())
next_peak.append(get_next_peak())
next_peak.append(next_peak[1] - next_peak[0])

答案 1 :(得分:0)

next_peak设为list

将输入转换为intfloat

next_peak = []
peakone = raw_input("Where is the next large peak?: ")
next_peak.append(int(peakone))
peaktwo = raw_input("Where is the next large peak?: ")
next_peak.append(int(peaktwo))
print next_peak[0] - next_peak[1] 

如果需要,可以将int更改为float