In the last exercise, you learned how to pause the program and allow the human to type in something. But what happened to what was typed? When you typed in the answer "Paris" for the first question, where did that answer go? Well, it was thrown away right after it was typed because we didn't put any instructions to tell the program where to store it. So that is the topic of today's lesson.
1 2 3 4 5 6 7 8 9 10 11 |
|
Just like the last exercise, when you first run this your program will only display the first question and then pause, waiting for a response:
Hello. What is your name?
Hello. What is your name? Brick Hi, Brick! How old are you? 25 So you're 25, eh? That's not very old. How much do you weigh, Brick? 192 192.0! Better keep that quiet!! Finally, what's your income, Brick? 8.75 Hopefully that is 8.75 per hour and not per year! Well, thanks for answering my rude questions, Brick.
We know from the previous exercise that the input()
function waits for the human to type something, then returns it as a string. We were throwing it away, but now we are storing it into the variable name. Nice and simple.
However, the input()
function always returns a string, no matter what type of thing they type in. This is nice and safe, since a string can hold anything.
But if we want to be able to do mathematics with what they give us, a string won't do. We need an int
or a float
.
So on line 5 we use the int()
to convert whatever they give us into an integer. This will work out great assuming they type a number with no decimals. (We'll mess with this in the Study Drills.)
We can do the same thing using the float()
function (line 7).
Does the program blow up if you enter an integer value when it is expecting you to type a double? Put an answer in a comment at the bottom of the code, along with your guess why or why not.
Does the program blow up if you enter a numeric value (int or float) when it is expecting a string? Put an answer in a comment at the bottom of the code, along with your guess why or why not.
Type something that makes the program blow up on every question possible, and add comments explaining what blew it up and why.
Add a new variable of your choosing. Add another question. (It doesn't have to be rude.) Let the human put an answer to your question into your new variable, and display the human's answer on the screen afterward.
©2017 Graham Mitchell