我是python的新手,我正在尝试制作一个应该是一个相对简单的函数。通过输入您驾驶的距离和使用的加仑气量,它将计算您的MPG。真的,这只是一个分裂问题。到目前为止我所拥有的是:
dist_traveled = raw_input ("How far did your car travel? (In miles?) ")
gas_consumed = raw_input ("How much gas did you use? (In gallons)")
def efficiency():
efficiency = dist_traveled/gas_consumed
return efficiency
efficiency = MPG
print MPG
我能做到的事实上是分裂。我正在使用python 2.7.5有人可以帮助/带我走过这个吗?感谢
答案 0 :(得分:3)
目前,您从raw_input
获得的用户输入只是一个字符串。您必须使用float
bultin函数将这些字符串转换为浮点数。此外,我建议更改您的功能,以便它采用输入参数而不是使用全局值。你必须正确地调用这个功能。
试试这个:
def efficiency(dist, gas):
return dist/gas
dist_traveled = raw_input ("How far did your car travel? (In miles?) ")
gas_consumed = raw_input ("How much gas did you use? (In gallons)")
MPG = efficiency(float(dist_traveled), float(gas_consumed))
print MPG
您可能还希望处理不正确的用户输入,即当用户输入无法解析为浮点数的内容时,例如,使用try/except
块和循环。
答案 1 :(得分:0)
def efficiency():
dist_traveled = float(raw_input ("How far did your car travel? (In miles?) "))
gas_consumed = float(raw_input ("How much gas did you use? (In gallons)"))
return dist_traveled/gas_consumed
print "%.2f" % efficiency()