簡體   English   中英

如何退回所有費用的總和?

[英]how do I return the sum of all of the costs?

因此,我從事代碼學院已有一段時間了。 我有一個作業,說我需要返回以前功能的費用總和。 因為這種方式行不通,我該怎么辦? 以及如何避免將來再遇到此問題?

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
nights = raw_input("How many nights are you staying? ")

raw_input返回一個字符串,您需要將其轉換為整數。 使用int(nights)

int()文檔

嘗試這個:

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)

不知道您使用此示例的方式...

您可以閱讀有關input()的內容

如果只希望整數作為輸入,請更改以下行:

nights = raw_input("How many nights are you staying? ")

至:

nights = int(raw_input("How many nights are you staying? "))

這將通過將int()強制轉換為raw_input()來糾正錯誤,該方法返回一個字符串。

>>> x = raw_input()
98
>>> type(x)
<type 'str'>
>>> x = int(raw_input())
23
>>> type(x)
<type 'int'>
>>> 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM