我是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并将此值保存为第三个。如果有的话,最好的方法是什么?
答案 0 :(得分:0)
你可以这样做:
peakthree = float(peaktwo) - float(peakone)
您从raw_input
获得的是一个字符串,因此您需要将其转换为数字类型,例如float
或int
。考虑编写这样的代码:
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
将输入转换为int
或float
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