Chapter 7: Input

In the previous examples, the age was placed right in the source code, on line 1:

age = 25

This is called hard-coding the age. The hard comes from the fact that once the program is written that way, the age is always 25. If the user wants to run the program with a different age, they need to change the source code. But that assumes that they understand programming. Since most users don’t understand programming, we’d really like to simply ask the user their age so that they never need to see the source code at all.

We can use a line like this:

age = input()

To input something means to put it into the computer. Output is the reverse, like the print statements we’ve been using.

So our program now looks something like this:

print "What is your age?"
age = input()
if age == 1:
    print "You are " + age + " year old."
    print "You are " + age + " years old."

When the user runs the program, instead of immediately seeing the “You are . . .” text, they’ll first see this:

What is your age?

and the system will appear to stop. The user will then be able to enter their age, press Enter, and the program will continue as it did before, with the variable age set to whatever number the user entered.

You may be curious about the set of parentheses after the word input. If you didn’t have those, like this:

age = input

the word input would look a lot like a variable. Since computers always want to be completely clear about what needs to be done, we add parentheses to mean, “This isn’t a variable, it’s a command. Do something clever.” input() is actually a function. We’ll cover functions later, but for now you can think of them as bits of code that do interesting things (like getting a number from the keyboard) and making some value available as a result (for assignment to age in this case). When the computer sees this line:

age = input()

It first sees the function input(), does the clever thing (gets a number from the keyboard), and replaces the function with the value that it got:

age = 25

(if the user typed 25). Then the assignment continues as it did before, storing the value 25 into memory and associating it with the word age.