为什么我不能将这个int类型变量作为Python中的参数传递?

时间:2016-11-25 17:45:55

标签: python python-2.7

以下是计算用户假期费用的三个功能。鼓励用户输入他的假期细节,然后将其作为参数传递给函数。

def hotel_cost(days):
    days = 140*days
    return days
"""This function returns the cost of the hotel. It takes a user inputed argument, multiples it by 140 and returns it as the total cost of the hotel"""

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
"""this function returns the cost of a plane ticket to the users selected city"""

def rental_car_cost(days):
    rental_car_cost=40*days
    if days >=7:
        rental_car_cost -= 50
    elif days >=3:
        rental_car_cost -= 20
    return rental_car_cost
"""this function calculates car rental cost"""



user_days=raw_input("how many days would you be staying in the hotel?") """user  to enter a city from one of the above choices"""
user_city=raw_input("what city would you be visiting?") """user to enter number of days intended for holiday"""


print hotel_cost(user_days)
print plane_ride_cost(user_city)
print rental_car_cost(user_days)

我注意到当我打印上面的函数时,只有plane_ride_cost(user_city)正确运行。另外两个功能吐出了胡言乱语。这是为什么?

2 个答案:

答案 0 :(得分:1)

您应该从user_daysint转换为str

def hotel_cost(days):
    days = 140*days
    return days


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):
    rental_car_cost=40*days
    if days >=7:
        rental_car_cost -= 50
    elif days >=3:
        rental_car_cost -= 20
    return rental_car_cost

user_days=int(raw_input("how many days would you be staying in the hotel?"))
user_city=raw_input("what city would you be visiting?")


print hotel_cost(user_days)
print plane_ride_cost(user_city)
print rental_car_cost(user_days)

答案 1 :(得分:0)

您需要将raw_input的输出转换为int。这应该有效:

user_days=int(raw_input("how many days would you be staying in the hotel?")) """user  to enter a city from one of the above choices"""

请注意,如果用户输入的数字不是数字,则会引发错误。