<p>这里有一些问题,但是首先,如果你的赋值允许,我会使用一个类而不是多个函数。我只需要创建一个大对象。原因是您有太多的参数,所以将参数传递给类,然后允许函数对其进行操作比将参数传递给多个函数更有意义。一切都是相似的,因为它都与旅行有关,所以我把它存储在一个类中。我使用的是Python3.6,因此它与您使用的Python2版本略有不同,但是您可以看到,我仍然需要将用户输入转换为整数值。在代码中,您不是将用户输入转换为整数值,而是尝试对数据执行数学运算。这也会给你一个回溯。您必须在原始输入之前定义数据类型。输入函数在Python2中的工作方式不会像在Python3.6中那样。但是,如果您曾经用Java编写过代码,它本质上就像声明一个变量。另外,在这里获取用户输入时,我会更改cities,以使用.lower()方法计算值。信任用户是有风险的。我在这里做了一些其他的改变,希望能有所帮助。你知道吗</p>
<pre><code>class BigTrip():
def __init__(self, nights, days, city, spending_money):
self.nights = nights
self.days = days
self.city = city
self.spending_money = spending_money
def hotel_cost(self):
self.hotel_cost = 140 * self.nights
return "Your hotel cost will be " + str(self.hotel_cost) + " dollars."
def plane_ride_cost(self):
if city.lower() == 'charlotte':
self.plane_cost = 183
elif city.lower() == 'tampa':
self.plane_cost = 220
elif city.lower() == 'pittsburgh':
self.plane_cost = 222
elif city.lower() == 'los angeles':
self.plane_cost = 475
return "Your plane cost will be " + str(self.plane_cost) + " dollars."
def rental_car_cost(self):
self.rental_cost = self.days * 40
if int(self.days) >= 7:
self.rental_cost -= 50
elif int(self.days) >= 3 and int(self.days) <7:
self.rental_cost -= 20
return "Your rental car cost will be " + str(self.rental_cost) + " dollars."
def trip_cost(self):
return "Your total trip cost will be: {} dollars".format(self.days + self.hotel_cost + self.plane_cost + self.spending_money)
nights = int(input("How many nights will you stay in the city?: "))
city = input('\nSelect a city[Charlotte, Tampa, Pittsburgh or Los Angeles]: ')
days = int(input('How many days will you be staying?: '))
spending_money = int(input('How much spending money do you have?: '))
my_trip = BigTrip(nights, days, city, spending_money)
print(my_trip.hotel_cost())
print(my_trip.plane_ride_cost())
print(my_trip.rental_car_cost())
print(my_trip.trip_cost())
</code></pre>
<p>以下是您的输出:</p>
<pre><code>How many nights will you stay in the city?: 4
Select a city[Charlotte, Tampa, Pittsburgh or Los Angeles]: charlotte
How many days will you be staying?: 3
How much spending money do you have?: 1200
Your hotel cost will be 560 dollars.
Your plane cost will be 183 dollars.
Your rental car cost will be 100 dollars.
Your total trip cost will be: 1946 dollars
</code></pre>