Python 我如何返回所有成本的总和?
所以,我做代码学院已经有一段时间了。我有一份作业,上面说我需要返回我以前工作的成本总和。因为这种方法不起作用,我该怎么做?我如何避免在将来遇到这个问题Python 我如何返回所有成本的总和?,python,Python,所以,我做代码学院已经有一段时间了。我有一份作业,上面说我需要返回我以前工作的成本总和。因为这种方法不起作用,我该怎么做?我如何避免在将来遇到这个问题 def hotel_cost(nights) nights = raw_input("How many nights are you staying? ") if nights == 0: return 0 elif nights > 0: return 140 * night
def hotel_cost(nights)
nights = raw_input("How many nights are you staying? ")
if nights == 0:
return 0
elif nights > 0:
return 140 * nights
def plane_ride_cost(city):
if city == "Charlotte":
cost = 183
elif city == "Tampa":
cost = 220
elif city == "Pittsburgh":
cost = 222
elif city == "Los Angeles":
cost = 475
return cost
def rental_car_cost(days):
days = nights
cost = days * 40
if days >= 7:
cost -= 50
elif days >= 3:
cost -= 20
return cost
def trip_cost(city, days):
return rental_car_cost(days) + plane_ride_cost(cost) + hotel_cost(days)
我得到这个错误:
hotel_cost(1) raised an error:
invalid literal for int() with base 10
raw\u input
返回字符串,需要将其转换为整数。使用int(夜间)
文档如果只需要整数作为输入,请更改以下行:
nights = raw_input("How many nights are you staying? ")
致:
这将通过将int()
强制转换为raw\u input()
(返回字符串)来修复错误
>>> x = raw_input()
98
>>> type(x)
<type 'str'>
>>> x = int(raw_input())
23
>>> type(x)
<type 'int'>
>>>
>>x=原始输入()
98
>>>类型(x)
>>>x=int(原始输入()
23
>>>类型(x)
>>>
试试这个:
nights = input("How many nights are you staying? ")
input()
返回一个int
我认为最好避免在函数中获取用户输入,在这种情况下,您可以在外部函数中收集所有信息,例如:
if __name__ == '__main__':
days = input('Something..')
nights = input('Something...')
city = raw_input('Something...')
# do whatever you want with data
print plane_ride_cost(city) + rental_car_cost(days) + hotel_cost(nights)
不知道您使用此示例的方式
您可以阅读您确定要在代码中使用nights=raw_input(…)行吗?代码的编写方式意味着您希望将住宿天数传递给函数hotel_cost。但是您正在使用原始输入调用中的字符串覆盖传入的nights值。您还应该提供完整的错误详细信息,因为这些信息告诉我们错误发生在哪一行。您还可以使用
input()
Nice标记。。。和:)如果某些东西适用于python-27和python-3.x,只需使用特定于版本的标记即可,这些标记仅用于不适用于其他版本的特定功能。10
已经是默认值。您不需要显式地提供它。@user2357112ta,我正在考虑另一种语言。我尝试了那个解决方案,但没有成功。代码行如下所示:nights=int(原始输入(“您要住几晚?”)
nights = input("How many nights are you staying? ")
if __name__ == '__main__':
days = input('Something..')
nights = input('Something...')
city = raw_input('Something...')
# do whatever you want with data
print plane_ride_cost(city) + rental_car_cost(days) + hotel_cost(nights)