Adding a string around the total trip cost


#1



Hello everyone,

My question is about the last part of lesson 8: Plan Your Trip!

I managed to write the code that the compiler accepts as the right answer, but was wondering how to change the output to something more than just the number 1955. Something like: "The total cost of your trip is $1955"

I tried using %d and %s, but that did not work. How would I get about this? Can't be that hard?

Thanks in advance,
Nirobie

def hotel_cost(nights):
    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):
    costs = 40 * days 
    if days >= 7:
        return costs - 50
    elif days >= 3:
        return costs - 20
    return costs

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

print trip_cost("Los Angeles",5,600)


#2

Hi!

When we print out the trip cost, we print out the result of calling trip_cost(), which returns an int. If you want to add additional information, you can simply add it to the print statement before calling the function.

There are a couple ways to do this:

  • This way utilizes print formatting with the % indication you mentioned (won't pass the compiler test, because it's looking for the trip cost in the form of an int):

print "The total cost is %i" % trip_cost("Lost Angeles",5,600)

  • Or, you can use concatenation (won't pass the compiler test):

print "The total cost is: $" + str(trip_cost("Los Angeles",5,600)

  • Lastly, you can use a comma to print on the same line but this one leaves an annoying space:

print "The total cost is: $",trip_cost("Los Angeles",5,600)

Output: The total cost is: $ 1955

**Note that this is the only one that passes the compiler test, because although you are adding a string to the output, 1955 still stays in int form!

Hope this helps your understanding!


#3

Thank you for the quick and clear answer! :slight_smile:

Nirobie


#4

Hi, @nirobie ,

@wowpalvabbit made some good suggestions.

Here's yet another technique for specifying the format of output, with the string format method, with 7 nights, for example ...

print "Your hotel bill: ${:0.2f}".format(hotel_cost(7))

Output, with 7 nights ...

Your hotel bill: $980.00

... or try this ...

def bill_printer(nights):
    print "Nights of stay: {:2d}".format(nights)
    print "Amount billed:  ${:0.2f}".format(hotel_cost(nights))

bill_printer(7)

Output ...

Nights of stay:  7
Amount billed:  $980.00

See str.format(*args, **kwargs).

(* Edited on July 12, 2016 to add bill_printer function example *)


#5

Hi @appylpye, (and @wowpalvabbit)

Thank you for the additional suggestions! I managed to apply your second suggestion to complete the code (see below), but this raises some new questions. Mostly to complete my understanding of how it works.

def bill_printer(city, days, spending_money):
    print "Your destination: {:s}".format(city)
    print "Nights of stay: {:d}".format(days)
    print "Additional money spent: ${:0.2f}".format(spending_money)
    print "Your hotel bill: ${:0.2f}".format(trip_cost(city, days, spending_money))

bill_printer("Los Angeles",5,600)
  • Why is there a colon in {:s} and the other used variants. Is this just syntax?
  • How does the float specify the amount of decimals? Is the 0 in 0.2 the number before the point, and 2 the amount of decimals? Because when I use {:2f} instead, it adds 6 decimals.
  • Should you not end every function with a return statement?
  • Is there a preferred way / best practice of executing this particular code, or does it really depend on the rest of the program / personal preference?

Thanks again! Hope I'm not asking to many questions..
Nirobie


#6

Hello again!

I'm sure @appylpye will have some great insight to this as well, but I'll give my initial thoughts.

To your first question: The formatting method I mentioned in my first post that utilizes the % operator is what you could call the "old school" approach to string formatting. It is common to the C++ language as well. Using the format() method is considered the "new" way to format strings in python, but really is calling the vformat() method.

See the documentation and additional explanation here!

For example, let's look at a line from my first post that uses the old-school formatting:

print "The total cost is %i" % trip_cost("Los Angeles",5,600)

Formatted with the newer way:

print "The total cost is {:i}".format(trip_cost("Los Angeles",5,600))

This looks a little more involved, but really the only change is that instead of indicating an int with %i, it is now indicated with {:i} ! So, to cut to the chase, yes - it is simply the syntax of the newer formatting.


You're right on target with your second point. Any numbers before the decimal point, when indicating a float, designate how many characters total your output should have. The numbers after the decimal point indicate how many should be after the decimal point in the output.

So, say we wanted an output of pi with at least 6 characters with zero-padding (to show the empty space before the number) and with 2 characters after the decimal point:

Input: '{:06.2f}'.format(3.141592653589793)
Output: 003.14

When you don't designate the numbers after the decimal, such as in your question, {:2f}, it just requires the output to be at least 2 characters long in total. So the float output defaults to the normal number of decimals, 6.

If we did something like {:2.0f}, that requires the output to be at least 2 characters long, with zero decimals. This would result in an output, in the case of pi, of _3 (with the underscore representing the space of padding).

In other words, we forced the output to have one space of padding since 3, with no decimals, only takes up one character, and we designated at least 2 in total.


Normally, functions do have a return statement, but it all depends on your intentions with the function. For example, it is useful to return a value if you plan on using the function later in your code as a parameter for something else.

A good example is in our trip_cost() function. This function returns a number and can be used in other methods, like a print method, or perhaps a yearly_expenses() function.

Other functions don't return anything if they simply perform a task or print something to the console. However, some may argue that it is good programming style to always have a return statement in your functions.


Lastly, referring to the bill_printer() function, you're absolutely right. The specific way you design the function and "best practices" depend on the rest of your program, preference, and the ultimate goal of the function. For example, we could re-write bill_printer() as a vacation_bill() function which returns a value instead of printing out all the parts of it, but that would only be useful if this was not the final part of a program!

As I said above, we could incorporate it into a yearly_expenses() function that has parameters as such:

print yearly_expenses(vacation_bill("Los Angeles", 5, 500) + amazon_orders(camera, TV, unicycle) + mortgage(12)) ...etc

But like you said, it depends on how modular you intend your program to be. If you only want to print out information to the console and don't intend on using the function again, it can make much more sense to simply print the results in the function (this can help with readability as well).


Hope this helps!

  • and PS, one of the best qualities of a successful programmer is the willingness to learn and ask questions! Don't ever hesitate to ask questions to improve your understanding. The nature of inquisitiveness is an excellent quality of any employee, so don't be discouraged :slight_smile:

#7

Thanks, @niroble , for the bill_printer function. It is a great example. I was actually considering suggesting that someone write a function that itemizes the costs of the trip, as a challenge, and you've already done it. Good work :slight_smile:

Thanks, @wowpalvabbit , for the explanation about how the various formatting techniques work.

Between the two of you, we have some great material for other users to work with for practice and experimentation.


#8

Hello!

Thanks @wowpalvabbit for the explanation and encouragement.

And @appylpye, I'm glad I made the first post with my initial question. Reading about how my little piece of code can also help others really motivates to continue learning. :slight_smile:


#9

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.