Now that we have practiced creating variables for a bit, we are going to look at the other part of interactive programs: letting the human who is running our program have a chance to type something.
1 2 3 4 5 6 7 |
|
When you first run this program, it will only print the first line:
What city is the capital of France?
...and then it will blink the cursor at you, waiting for you to type in a word. When I ran the program, I typed the word "Paris", but the program will work the same even if you type a different word.
Then after you type a word and press Enter
, the program will continue, printing:
What is 6 multiplied by 7?
...and so on. Assuming you type in reasonable answers to each question, it will end up looking like this:
What city is the capital of France? Paris What is 6 multiplied by 7? 42 Enter a number between 0.0 and 1.0: 2.3 Is there anything else you would like to say? No, there is not.
Compared to some other programming languages, getting input from the human is pretty darn easy in Python.
It will get a little more complicated soon, but not much. You provide the input()
function a message or "prompt". Python will show the prompt on the screen and then pause, waiting for the human to type something. Whatever they type is packaged up into a string and returned to your code.
At the moment we are ignoring what it gives us.
Line 2 is a bit weird, though. Python 2 had two ways to get input from the user: an input()
function and a raw_input()
function. In Python 2, raw_input()
was the good one and input()
was kind-of broken. In Python 3, input()
is the good one, and raw_input()
doesn't exist anymore.
So, since we are using Python 2 in this class to learn Python 3, we have to type input = raw_input
at the top. Weird. But you'll get used to it.
Add a new question at the bottom of the code.
What happens if you remove print_function future import from the top? Try it out, and answer in a comment.
©2017 Graham Mitchell