yego.me
💡 Stop wasting time. Read Youtube instead of watch. Download Chrome Extension

Type casting | Intro to CS - Python | Khan Academy


3m read
·Nov 10, 2024

Have you ever tried to make your print output a bit more descriptive, like this, only to get a type error? Why does that happen, and how do we fix it?

Let's put our debugging skills to work. We saw that my program last worked when I was just printing the average score. It's only when I tried to add this string at the front that I started getting an error. This error message tells me the computer is having trouble concatenating a string with a float. My average quiz score is a string, and the variable average score contains the value 89.5, which is a float. We know that computers can't add strings and floats together; they can only concatenate strings and strings or add some combination of integers and floats.

Okay, so we know why we're getting that error, but what can we do about it? We, as the programmers, need to help the computer out here. The computer is very stubborn about its data types matching, and we can't change that, but we can change our values to be different data types. This is called type casting, where we convert or cast a value from one data type to another data type.

To cast a value to a string, we use the string function. Remember that a function takes in an input value, performs some actions on it, and then returns an output value. With the string function, our input value is the value that we want to cast to a string, and our output value is that input value as a string.

Casting a float or an integer to a string is pretty straightforward; it's just as if we put quotation marks around it. Back to our program: all we have to do is call the string function on average score. Then, that float value 89.5 that the average score variable contains will be cast to the string "89.5". If we ignore the variable for a second, this is the same as saying "plus 89.5", which does give a type error, versus "string 89.5", which doesn't give a type error. Once we have this expression with two strings, the computer can just concatenate them.

What if I want to see how my next quiz score will affect my average? I might add an input prompt here to let me enter in different scores. So, I update my average score calculation to include that new score, and now I'm getting a type error again. That's because the output value that the input function returns is always a string, even if what the user typed kind of looks like a number. That means, over here on the second line, when I'm trying to add new score, I'm once again adding floats and strings. Instead, I want that quiz score to be an integer so I can do some math with it.

To cast a value to an integer, we use the int function. If I start with a string value like "89" and I cast it to an integer, I'm effectively just removing the quotation marks around it, so now I have 89. Do you see any problems here? Well, based on the previous quizzes, it seems that we support half points, like 89.5; that might be a quiz score, and 89.5 is a float, not an integer. If I enter 89.5 at the prompt, we get a value error because we're trying to cast the string "89.5" to an integer.

This means that we probably shouldn't be casting to an integer; instead, we should cast to a float. To cast a value to a float, we use the float function. We might also move that type cast up here so the value is already converted to a float before it's stored in the variable new score. Then we don't have to remember later to cast the value of new score to a float anytime we access it.

Put that all together, and we can cast values using the string function, the int function, and the float function. Also note, there is a bool function that converts values to booleans. If we try to cast values that just don't make sense, as you saw, we get a value error. This is like if I tried to cast the string "banana" to an integer or the string "9.9.9" to a float; it's just not possible in any meaningful way. Like, what should "banana" be as an integer? I don't know.

Now, what about casting a float to an integer? It turns out this just chops the decimal portion off, so 3.8 becomes 3. We're taking the floor or the lower closest integer. So next time you see a type error in your program, check the data types in your expressions and make sure they match: strings with strings and integers and floats with integers and floats. If you need those values to be a different data type, you can always cast them.

More Articles

View All
2015 AP Calculus AB 2a | AP Calculus AB solved exams | AP Calculus AB | Khan Academy
Let f and g be the functions defined by ( f(x) = 1 + x + e^{x^2 - 2x} ) and ( g(x) = x^4 - 6.5x^2 + 6x + 2 ). Let R and S be the two regions enclosed by the graphs of f and g shown in the figure above. So here I have the graphs of the two functions, and …
Philip of Macedon unifies Greece | World History | Khan Academy
The 5th century in Greece started off with the Persian invasion and ended with the Peloponnesian War. Now we’re entering into the 4th century in Greece. As we entered the 4th century, Thebes is the dominant city-state. However, as we get into the mid-4th …
5 ways to avoid taxes...legally
What’s up, you guys? It’s Graham here. So, the time is fast approaching, and that would be the dreaded April 15th tax deadline. This is the deadline for filing your tax return and submitting any payment you might owe to the IRS or to the state. I get it;…
The Last Days of the Romanovs | National Geographic
I think it’s a big tragedy, big tragedy for the country and for the world. For 300 years, the Romanovs ruled Russia as czars—loved, feared, revered, respected. But all too often, those who fly highest fall furthest. World War One brought Russia to revolut…
Breaking Down HackerRank's Survey of 40,000 Developers with Vivek Ravisankar
All right, the Veck, why don’t we start with what you guys do, and then we’ll rewind to before you even did YC? Yes, sure! I’m S. V. Ivent, one of the founders and CEO of HackerRank. Our mission at HackerRank is to match every developer to the right job,…
Finding inverse functions: radical | Mathematics III | High School Math | Khan Academy
[Voiceover] So we’re told that h of x is equal to the negative cube root of three x minus six plus 12. And what we wanna figure out is, what is the inverse of h? So what is… What is h inverse of x going to be equal to? And like always, pause the video and…