…
…
Python Programming Fundamentals · Lesson 4 / 40 · Strings, types, and conversion
PreviewIn this lesson you will
int() and float() and calculate the amountYou can read the explanation without an account. The exercises and quiz at the end of the lesson are for members.
The Corner Café order screen sends the quantity as "2" and the price as "3.75"; both look like numbers on the screen, but they are actually strings. Ada wants to calculate the amount from these two values and print a neat receipt line with the item name on the left and the amount on the right. In this lesson we will build that line together.
The output of the program you write at the end of the lesson will be this single line:
OutputBrownie 7.50It looks simple: an item name, some space, and an amount. But to get to this line you need to know three things. First, that every value in Python has a type, and that the same operator does different jobs depending on the type. Second, how to convert a string that comes from outside into a number you can do math with. Third, the f-string syntax that lets you print the result the way you want, with two decimal places and aligned. You will learn these three steps in order, each with an example and by trying it yourself.
In the earlier lessons you saw two kinds of values: strings inside quotes ("Latte") and numbers without quotes (85, 3.75). Now we go one step further: 85 and "85" look the same on the screen, but for Python they are completely different things. The first is an integer; the second is a string two characters long, made of the characters 8 and 5. Python understands what a value is by looking at its type. In this lesson we will use three types: str (short for "string") for strings, int for integers, and float for floats.
Why does the type matter? Because the same operator does different jobs depending on the type. + between two numbers adds: 85 + 1 is 86. + between two strings does not add; it puts the strings end to end (it concatenates them): "85" + "1" is "851". The multiplication operator behaves in a similar way: if you multiply a string by a number, the string is repeated that many times. "3" * 2 is not six, it is "33". This may look odd, but it is useful: by writing "-" * 20 you can draw a line of twenty hyphens at the bottom of the receipt.
If you are not sure of a value's type, you can ask Python. The type() function tells you the type: type("85") gives <class 'str'>, and type(85) gives <class 'int'>. Another useful function for strings is len(): it counts how many characters a string has. A space is a character too, so len("Corner Café") is 11 (six letters, one space, four letters).
Example 1: The same operator, different types
print(85 + 1) print("85" + "1") print("3" * 2) print("-" * 20) print(type("85")) print(type(85)) print(len("Corner Café"))
Output86
851
33
--------------------
<class 'str'>
<class 'int'>
11Look at the output line by line. On the first line, two numbers were added. On the second line, two strings were put side by side. On the third line, the string "3" was repeated twice. The last three lines show the type and the length. Now it is your turn: predict the output of the code below without running it.
What does this code print?
print("3" + "4")
The fastest way to recognize a type is to look at the quotes and the decimal point. If there are quotes, the value is a string no matter what is written inside. If there are no quotes and there is a decimal point, it is a float; if there is no decimal point, it is an int. Careful: even though 3.0 and 3 have the same value, their types are different; because it is written with a decimal point, 3.0 is a float.
Match each value with its type.
For each row, pick its match from the list, then check.
853.75"85"3.0"3.0"Variables carry these labels too. If you put a string into a variable, the variable's type is str; if you put in an integer, it is int, and if you put in a float, it is float. Follow the code below step by step and watch what the type label says in each variable box. On the last line, check by counting the letters why the result of len(item) is 5.
Run the code line by line: see which line runs next, the variable boxes and the output.
item = "latte" price = 4.25 print(type(item)) print(type(price)) print(len(item))
A common misunderstanding is to think that "3" * 2 will give 6. Python looks at whether the number is inside quotes; if it is, it sees it not as a number but as a piece of writing, and it repeats the writing.
The 85 that you write inside the code is already a number. But values that come into the program from outside, that is, values that the user types on the keyboard, that are read from a file, or that are sent from a web form, almost always arrive as strings. The Corner Café order screen also sends the quantity as "2". If you try to do math with this string, you either get an error or a wrong result: "2" * 3.75 raises an error, while "2" * 3 quietly produces "222". That is why you need to convert the string into a number before doing the math.
Python offers three functions for this, named after the types:
| Function | What it does | Example | Result |
|---|---|---|---|
int() | Converts to an integer | int("3") | 3 |
float() | Converts to a float | float("3.75") | 3.75 |
str() | Converts to a string | str(85) | "85" |
int() | Drops the decimal part of a float | int(37.9) | 37 |
You decide which function to choose by looking inside the string. For a string without a decimal point, like a quantity, you use int(); for a string with a decimal point, like a price, you use float(). If the result is going to be a string that shows on the screen, for example if you want to add a number to the end of a label, you use str().
Example 2: An order from the screen
qty_text = "2" price_text = "3.75" amount = int(qty_text) * float(price_text) print("Total:", amount)
OutputTotal: 7.5Here int(qty_text) produced the number 2 from the string, and float(price_text) produced the number 3.75. Because the product is a float, the result was printed as 7.5. Conversion in the opposite direction is needed too: when you want to add a number to a string, you convert the number into a string with str().
Example 3: Table label
table = 7 label = "Table " + str(table) print(label) print(type(label))
OutputTable 7
<class 'str'>int() cannot convert every string. It ignores spaces at the start and the end, so int(" 3 ") works without a problem. But if the string does not show an integer, for example if it has a decimal point inside ("3.5") or if the number is written in words ("three"), Python raises a ValueError. In the block below, change the entry value and see for which values the program stops. For the values that raise an error, you will see that the third line stays dimmed, that is, it never runs.
What does int() do if the user types different things?
Pick a value; predict the output first, then look.
1entry = "3"2qty = int(entry)3print(qty * 1.25)
3.75
Faded lines didn't run with this value. int() ignores a space at the start and the end. It cannot convert a string with a decimal point or a number written in words; on the second line it raises a ValueError and the program stops there. For a string with a decimal point, you use float().
The most overlooked property of conversion is this: int(), float(), and str() do not change the variable you have; they produce a new value. Writing int(qty_text) does not turn the string in the qty_text box into a number; if you want to use the number that was produced, you have to put it into a variable: qty = int(qty_text). The rule you saw earlier for round() applies here too: if you do not assign the result, it is lost. Follow the code below step by step and notice that the type of the qty_text box stays str even at the very end. That is why the fourth line prints 33 and not 6.
Run the code line by line: see which line runs next, the variable boxes and the output.
qty_text = "3" qty = int(qty_text) amount = qty * 1.25 print(qty_text * 2) print(amount)
There is one more misunderstanding: int() does not round a float, it cuts off its decimal part. Test this with a prediction.
What does this code print?
print(int(9.99))
In short, do the conversion right where the data enters the program, and keep the result under a new name (qty, price). That way you do not have to think about the type in the rest of the program.
Now you can calculate the amount, but printing it on a receipt is a separate job. The output of print("Total:", amount) is Total: 7.5; for a money amount, a single decimal place looks odd, and when items come one under another the digits do not line up. Joining strings with + is also tedious, because you have to convert every number with str() first. The syntax that solves all of this at once is the f-string.
To write an f-string, you put the letter f right before the quote. Inside the string, where a value is to go, you write a variable name or a calculation inside curly braces: f"Total: ${amount}". Python calculates what is inside the braces and puts the result into the string. You do not need str() to turn the number into a string.
Inside the curly braces, after the value, you can put a colon and say how it should look. The most commonly used format is :.2f: it shows the number with two places after the decimal point (rounding if needed). f"{12.5:.2f}" gives 12.50. What matters is this: a format only changes how it looks on the screen; it does not change the value of the variable. After printing with a format, amount is still 12.5.
Example 4: Putting values and a calculation into the form
item = "Latte" qty = 2 price = 4.25 print(f"{qty} x {item} = ${qty * price}") amount = 12.5 print(f"Total: ${amount:.2f}") print(amount)
Output2 x Latte = $8.5
Total: $12.50
12.5The last line is the proof that the format did not change the value: amount is still 12.5. Now test what the format does with a prediction.
What does this code print?
print(f"{3.14159:.2f}")
There is one more problem on a receipt: alignment. Item names have different lengths (Tea is three letters, Cookie is six), so the amounts printed right after the name do not line up one under another. The solution is to set aside a fixed-width field for each value. :<10 writes the value into a ten-character field, left-aligned, and fills the rest with spaces. :>8 right-aligns it in an eight-character field. You can combine the two formats: :>8.2f writes the number in an eight-character field, right-aligned and with two places. When the item name is on the left and the amount is on the right, the digits stand one under another just like on a real receipt.
Example 5: Mini receipt
print(f"{'Latte':<10}{8.5:>8.2f}") print(f"{'Cookie':<10}{2:>8.2f}") print("-" * 18)
OutputLatte 8.50
Cookie 2.00
------------------Latte is five letters, its field is ten characters; the remaining five characters were filled with spaces. Then 8.50 is four characters, its field is eight; four spaces were added in front. That way every line became exactly eighteen characters, and the line was drawn with eighteen hyphens, the same width. In the block below, change the item name and the amount: see that even when the name gets longer or shorter, the amounts always stay in the same column. When you choose 1250.5, 1250.50 is seven characters and only one space is left at the start of the eight-character field; the digits still end in the same place.
How does the receipt line look when the item name or the amount changes?
Pick a value; predict the output first, then look.
1item = "Latte"2amount = 8.53print(f"{item:<10}{amount:>8.2f}")4print(f"{'TOTAL':<10}{amount:>8.2f}")
Latte 8.50 TOTAL 8.50
Faded lines didn't run with this value. :<10 left-aligns the name in a ten-character field, and :>8.2f right-aligns the amount in an eight-character field and writes it with two places. Because the width of the fields is fixed, the amounts stay in the same column however long the name is (as long as it does not go over ten characters).
The sneakiest trap of the f-string is forgetting the f before the quote. In this case Python does not raise an error; it prints the curly braces and what is inside them as they are. The code below is missing the f. First run it and look at the output, then add the missing letter and run it again. After that, add a line and print amount = 8.5 in the form Total: $8.50 with :.2f.
Try it now· not graded; doesn't affect progress
One last misunderstanding to watch for: :.2f does not change the value of the variable permanently. If you really want to round the value to two places, you use round(amount, 2); if you only want to see two places on the screen, :.2f is enough. On receipts, the second is usually what you want.
Now you have put the three steps together: convert the string from outside, calculate, print with a format. The examples below show the same three steps first in a setting outside the café, and then in a receipt line from start to finish.
An average that comes from the school system is a string too. First convert it, then print it with one decimal place.
name = "Alex" average_text = "84.456" average = float(average_text) print(f"{name}: {average:.1f}")
OutputAlex: 84.5A notebook line at the stationery shop: convert the strings, calculate the amount, align the item to the left and the amount to the right. The steps are named with comments; you will use the same steps in the exercises.
# 1. Convert the strings that come from outside item = "Notebook" qty = int("3") price = float("2.5") # 2. Calculate amount = qty * price # 3. Print with a format print(f"{item:<10}{amount:>8.2f}")
OutputNotebook 7.50Joining a string and a number with `+`. If you write print("Total: " + total) when total = 11, Python stops and raises TypeError: can only concatenate str (not "int") to str: it means "only a string can be added to a string, and you gave an int". The correct ways: print("Total: " + str(total)), print("Total:", total), or print(f"Total: {total}").
Forgetting the `f` in an f-string. print("Total: ${total}") does not raise an error, but it prints Total: ${total} on the screen; the curly braces stay as they are. Because there is no error message, it is hard to notice; you catch it by reading the output. The correct way: print(f"Total: {total} dollars").
str, int, float); + adds numbers and joins strings, and * repeats a string. type() tells you the type, and len() tells you the number of characters in a string.int() or float() and assign the result to a variable; int() raises a ValueError on a string with a decimal point, and it does not round a decimal, it cuts it off.f"...{value}...") puts values into a string; :.2f gives two places, :<10 and :>8.2f give fixed-width aligned fields, and none of them changes the value of the variable.Next lesson: In this lesson you saw two error messages; in the next lesson you will learn to read error messages systematically and to get help from them.
Exercises and quiz are for members
This lesson has 7 coding exercises and a 10-question quiz. Sign up free to solve them, save your progress and move on to the next lesson.