如何在Python中给出要打印的函数的返回值

时间:2015-01-30 04:40:24

标签: python

我是python的新手,我正在尝试编写一个简单的假期程序。在我的程序中,用户需要输入城市,度假天数等...最后我根据几个函数中定义的一些简单计算计算总成本。

我的问题是,我无法打印具有两个输入参数的特定函数的输出,而无需在print语句中添加输入参数!!!

但是,由于用户输入了值,我不想对它们进行硬编码。

def trip_cost(city, days,spending_money): 
  city = hotel_cost(days) + plane_ride_cost(city) 
  days = rental_car_cost(days) 
  total_cost = city + days + spending_money 
  return total_cost 

我是新人,输了!!!

请帮帮我....

4 个答案:

答案 0 :(得分:1)

您的函数返回一个值,该值可以作为参数传递给print()或格式化字符串。例如:

print("Your %s day trip in %s is %0.2f dollars"%(days, city, trip_cost(city, 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 
    else:
        raise ValueError("No Vacation")

def hotel_cost(days): 
    return 140*days

def rental_car_cost(days):
    return 30*days

def trip_cost(city, days):
    total_cost = 0.0
    total_cost += hotel_cost(days)
    total_cost += plane_ride_cost(city)
    total_cost += rental_car_cost(days)
    return total_cost

city=raw_input("Enter your destination")
days=int(raw_input("Enter the duration of your stay in number of days"))
print("Your %s day trip in %s is %0.2f dollars"%(days, city, trip_cost(city, days)))

答案 1 :(得分:0)

我不确定我是否理解您的问题,但您可以按照以下方式打印特定值:

print("City: %s\nDays: %s\nSpending money: $%s\n") % (city,days,spending_money)

假设输入分别为:NYC,10和12345,则输出为:

城市:纽约

天数:10

花钱:12345美元

答案 2 :(得分:0)

请准确说明您要打印的内容以及您正在使用的python版本。

def trip_cost(city, days, spending_money):
    total_cost = hotel_cost(days) + plane_cost(city) + rental_car_cost(days) + spending_money 
    print "Total Cost: " + str(total_cost)
    return total_cost

答案 3 :(得分:0)

我假设您要计算总费用。然后在Python 3中:

hotel_cost_amt = 200
rental_car_amt = 30
plane_ride_amt = {'city_A': 1200, 'city_B': 1100}

def hotel_cost(days):
    return days * hotel_cost_amt

def plane_ride_cost(city):
    return plane_ride_amt[city]

def rental_car_cost(days):
    return rental_car_amt * days

def trip_cost(city, days,spending_money): 
    return hotel_cost(days) + \
        plane_ride_cost(city) + \
        rental_car_cost(days) + \
        spending_money

if __name__ == '__main__':
    days = 7
    city = 'city_A'
    spending_money = 2000

    print('Your trip cost for %i many days of stay in %s, when you rent a car for %i number of days is %i. This includes %i spending money.' % \
        (
            days,
            city,
            days,
            trip_cost(city, days, spending_money),
            spending_money
        )
    )

你定义它的方式不起作用。对于Python 2,请使用

print 'Your trip cost for %i many days of stay in %s, when you rent a car for %i number of days is %i. This includes %i spending money.' % \
        (
            days,
            city,
            days,
            trip_cost(city, days, spending_money),
            spending_money
        )