<p>试试这个:</p>
<pre><code>def hotel_cost(nights):
return 140 * nights
def plane_ride_cost(city):
if city == "Charlotte":
return 183
elif city == "Tampa":
return 220
elif city == "Pittsburgh":
return 222
else:
return 475
def rental_car_cost(days):
cost = days * 40
if days >= 7:
cost = cost - 50
elif days >= 3:
cost = cost - 20
return cost
def trip_cost(city, days):
city = raw_input("What city are you travelling to?")
days = raw_input("How many days are you staying?")
total_cost = hotel_cost(int(days)) + plane_ride_cost(city) + rental_car_cost(int(days))
print total_cost
if __name__ == '__main__':
trip_cost(None, None)
</code></pre>
<p>解释一下:
<code>raw_input</code>会给你一个字符串。
如果要对从原始输入得到的值进行算术运算,则需要将其转换为整数。你知道吗</p>
<p>另外,如果您试图从命令行运行此命令,则需要下面两行。你知道吗</p>
<p>你真的应该替换:</p>
<p><code>def trip_cost(city, days)</code></p>
<p>与</p>
<p><code>def trip_cost()</code></p>
<p>因为您不是从传递到方法中的参数填充city和days值,而是使用原始输入从控制台获取这些值。你知道吗</p>
<p>如果你这样做了,那么改变:</p>
<p><code>trip_cost(None, None)</code></p>
<p>至</p>
<p><code>trip_cost()</code></p>
<p>所以说了这么多,我最终还是要重写它:</p>
<pre><code>def hotel_cost(nights):
return 140 * nights
def plane_ride_cost(city):
if city == "Charlotte":
return 183
elif city == "Tampa":
return 220
elif city == "Pittsburgh":
return 222
else:
return 475
def rental_car_cost(days):
cost = days * 40
if days >= 7:
cost = cost - 50
elif days >= 3:
cost = cost - 20
return cost
def trip_cost():
city = raw_input("What city are you travelling to?")
days = raw_input("How many days are you staying?")
total_cost = hotel_cost(int(days)) + plane_ride_cost(city) + rental_car_cost(int(days))
print total_cost
if __name__ == '__main__':
trip_cost()
</code></pre>
<p>输出结果如下:</p>
<pre><code>(cost)macbook:cost joeyoung$ python cost.py
What city are you travelling to?Pittsburgh
How many days are you staying?4
922
</code></pre>