Work With Strings and Numbers (Solution)
As you can see, it’s of class
str. It looks like that. So if you’re collecting user input, it’s always going to arrive as a string. And then if you’re trying to multiply two strings together, you’re going to run into an error.
01:28 There’s a little fun thing on the side though. If you had a different program that had a fixed integer that you’re multiplying the user input with, let’s say, then if you don’t do a type conversion here, you could run into an output that you might not expect.
02:18 And that works out, right? That works correctly, and math makes sense again. So that’s just to keep in mind that you will need to convert these numbers. With that, let’s get started by collecting the two numbers from the user.
You can’t do concatenation if not both of them are strings. So in order to be able to display this message,
of", here you can just use the variable that I’ve collected because
a is a string, right?
and now if I just add the
product here without any conversion, I’d again run into an error. Let’s try that out in the console. So here what I’m trying to do is concatenate a string and a floating-point number.
So it’s marked it over here. I’m going to say
"a", this is my string, plus a floating-point number,
0.2. And you can see that Python again gives a
TypeError where it tells you that it can only concatenate strings to strings and not a float to a string.
The result of the input looks like a floating-point number, but here in the
print() call, you’re converting it to a string before concatenating it with the other pieces of the string that you’re assembling.
Become a Member to join the conversation.