Sal's Shipping question

Here is the final code for the last task on the lesson. Can someone explain or point me to a resource on the section of the code that uses %? What does this mean?

Any guidance will help!

def print_best_option(weight):
ground = ground_shipping(weight)
drone = drone_shipping(weight)
premium = premium_shipping

if ground < premium and ground < drone:
method = “Standand Ground”
cost = ground
elif premium < ground and premium < drone:
method = “Premium Ground”
cost = premium
else:
method = “Drone Delivery”
cost = drone

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

Hello!

This is a type of string formatting. The % indicates to the program that there should be another value here, which is stored in a variable. When you have %(var_name, var_other_name) at the end, it signifies the order in which the variables should be implanted into the string. Here is some reading on it.

I hope this helps!

2 Likes

This does immensely help!

2 Likes

So let me get this straight, the % Operator helps bring in “outside” variable into a string to aid in string concatenation? Making me not have to write a print statement with a bunch of str() and +'s?

Sorry for the newb questions.

It’s the slightly older version of string formatting (earlier Python2) which does allow you to convert multiple variables to a string format with a degree of control over how they’re converted. I quite lke this page as an introduction to formatting methods-
https://pyformat.info/

If I’m not mistaken we inherited modulo formatting from C.

Why it would show up in a Python 3 course is beyond me. Is this a Python 2 free course?

mtf, it’s a lesson in the Python 3 section of “Control Flow”.

In the future we will probably lean on f-string for string interpolation. I believe it is supported in the Python 3 track. Look into it.

mtf, thank you! I just found this online resource (https://realpython.com/python-f-strings/).

I do have one more question if you don’t mind me taking up more of your time…
I like that codeacademy allows you to code within the webpage but how do I setup my Mac to have a standalone terminal to write code and see the output when ran?

Again, I apologize for the simple question.

Hello again. This might not be much help, but if you search in spotlight for IDLE, which is a Python text-editor, if it’s there, then you can use that easily.

1 Like