Explaining Sal's Shipping

Having some real trouble understanding this exercise. I’m watching the project walkthrough and it starts questions six by saying to write the statement:

"print (“The cheapest option available is %.2f with $s shipping.”) % (cost, method)

Could someone explain the logic of this statement? I don’t understand where the % symbol or the (cost, method) were supposed to come from in the lesson. I don’t remember learning about them in any of the previous exercises either. Any help is appreciated.

You must select a tag to post in this category. Please find the tag relating to the section of the course you are on E.g. loops, learn-compatibility

When you ask a question, don’t forget to include a link to the exercise or project you’re dealing with!

If you want to have the best chances of getting a useful answer quickly, make sure you follow our guidelines about how to ask a good question. That way you’ll be helping everyone – helping people to answer your question and helping others who are stuck to find the question and answer! :slight_smile:

Hi there, welcome to the forums!

What you’re seeing is an example of printf-style formatting.

In your string, %.2f is a placeholder. It tells Python to write a float, and that it should write it to two decimal places. The %s is another placeholder, this time telling Python to write a string value.

At the end of the string, you tell Python that you’re going to pass the values to those placeholders with the % operator. (% is usually referred to as the “modulo” operator; in this context, it’s more accurate to call it an interpolation operator as that’s what it’s doing.)

The values in the tuple after the % are what Python will print instead of the placeholders.

So, in your example:

print("The cheapest option available is %.2f with %s shipping." % (cost, method))

Python will replace %.2f with the value of cost, replace %s with the value of method, and print the entire thing to the console.

If cost = 76.4325, and method = ground, you’d get back “The cheapest option available is 76.43 with ground shipping.

When you put it all together, you have a simple way of dynamically putting values into a string without having to do a load of concatenation with +.

Does that help at all? :slight_smile: Let me know if I’ve not explained very well.

Yes it did help! Thank you! My only other thing is, how am i supposed to know pritnf-style formatting if the lessons haven’t covered it?

I would assume it’s covered somewhere in the course, but perhaps not at any great length.

If I remember rightly, it’s definitely covered in the Python 2 stuff. I haven’t done the Py3 course, so can’t say for sure whether it’s covered in any detail.

Either way, you eventually came to the forums and asked us. :slight_smile: