[英]Traceback (most recent call last): and TypeError:
我仍然是Python的初學者,目前正在使用codecademy。 我決定稍微簡化其中一個練習程序,但遇到了這個錯誤:
Traceback (most recent call last):
File "python", line 30, in <module>
File "python", line 24, in trip_cost
File "python", line 18, in rental_car_cost
TypeError: unsupported operand type(s) for -: 'unicode' and 'int'
這是我的代碼:
def hotel_cost(nights):
# the hotel costs $140 per night
return 140 * nights
def plane_ride_cost(city):
if city == "Charlotte":
return 183
elif city == "Tampa":
return 220
elif city == "Pittsburgh":
return 222
elif city == "Los Angeles":
return 475
def rental_car_cost(days):
cost = days * 40
if days >= 7:
cost -= 50
elif days >= 3 and days < 7:
cost -= 20
return cost
def trip_cost(city, days, spending_money):
return rental_car_cost(days) + hotel_cost(days - 1) + plane_ride_cost(city) + spending_money
x = raw_input("Where are you going? ")
y = raw_input("How many days are you going for? ")
z = raw_input("How much spending money are you taking? ")
print trip_cost(x, y, z)
任何幫助將不勝感激,謝謝! 我是一個初學者,所以我的python術語有點生銹。
您正在做days - 1
或cost -= 50
但是days
和cost
是用戶輸入,因此是一個字符串(在您的情況下,unicode字符串更准確),您應該在執行任何操作(尤其是數學運算)之前將其轉換為int
,因為這是您的意圖:
y = int(raw_input("How many days are you going for? "))
z = int(raw_input("How much spending money are you taking? "))
這是因為您將它們當作數字使用,而沒有轉換
但是請注意,輸入數字以外的任何數字都會產生錯誤,但這是另一個問題的主題
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.