Prompt the User
00:00
Now it’s time to tackle the last to-dos that are here. You edit the 72
and the 37
as values for temp_far
and temp_cel
.
00:09
But actually, you want to prompt the user to input a number. So the value of temp_far
should be a call of the input()
function.
00:19
And for now, just add something like "F:"
. You can bother about making it nice in a moment. For now, let’s just use the input()
function to prompt the user and see if our code works as it is.
00:32
So when you run the module, then you’re prompted with F:
, you add a Fahrenheit number, and then you get an error.
00:41
Okay, let’s have a look at the error. It’s a TypeError
that says you have an unsupported operand type for -
between str
and int
in line 8, which is inside of the convert_far_to_cel()
function.
00:58
So if you have a look at line 8, then you have the expression temp_far - 32
.
01:07
Now coming back to the error again, it says that you are doing something with a str
and an int
. Maybe you know a little bit about the input()
function, and you already know why this error now occurs.
01:20
The reason for this is that input()
always returns a str
. So even if you added 72
, which looks like a number, the return value from the input()
function will be a str
.
01:33
So you are trying to subtract the int
32
from the str
"72"
here, which obviously doesn’t work.
01:44
So what you need to do is you need to convert what the input()
function gives you back into a number value as well, and more specifically, into a float
.
01:54
So wrap both input()
function calls into a call to the built-in float()
function. So temp_far = float()
, and then the input()
call.
02:06
And now when you run the script, you can add in 72
, and there is no error, but the error still occurs when you add something to the "C:"
because there you haven’t wrapped the float()
yet.
02:18
So let’s do this as well. temp_cel = float()
, and then the input()
call. And don’t forget to put a closing parenthesis at the end of the line.
02:31
And now when you run the module again and add 72
for the Fahrenheit and 37
for the Celsius, then the result is as expected. That’s good news. So with the float()
function call, you convert the input, which comes in as a str
, into a float
, and then all your calculations work.
02:55 You can remove the comment that stated the task.
03:00 Next, the only thing that’s left is making all those strings and input requests a bit more readable, so you have a nicer message there.
Become a Member to join the conversation.