【问题标题】:Why can't I pass this int type variable as an argument in Python? [duplicate]为什么我不能将此 int 类型变量作为 Python 中的参数传递? [复制]
【发布时间】:2016-11-26 01:54:59
【问题描述】:

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

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) 可以正常运行。其他两个函数吐出乱码。这是为什么呢?

【问题讨论】:

标签: python python-2.7


【解决方案1】:

您应该将 user_daysstr 转换为 int

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)

【讨论】:

    【解决方案2】:

    您需要将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"""
    

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-08-16
      • 1970-01-01
      • 2012-12-30
      • 1970-01-01
      • 1970-01-01
      • 2022-07-16
      相关资源
      最近更新 更多