Saturday, November 12, 2011

Having fun with keyboard input

Time to take a small break, a quick detour. How do you interact with Python? Up to this point we've written instructions in the Python interpreter and Python has displayed the results immediately. We'll soon get to the point where we need to write programs, more than a single or a few lines, that will require that we write the programs outside the Python interpreter and ask Python to load them from there.

But in this note, I'd like to concentrate on Python's ability to accept input from the user. You.

Look at the following example.


We use the Python function raw_input(). raw_input() takes a single argument, a prompt that you wish to display. The argument isn't necessary. If you don't provide one, then Python won't display a prompt.

In our example, we call raw_input() and provide the prompt "Type something: ".

We then store the result in a variable, "a".

Here's an example where we get two numbers from the user, and then add them.


A few things to note from this example.

The return value of the raw_input() function is a string. Even though we typed in numbers, 12 and 5, they were stored in the string variables a and b. So, in order to add them, we have to use the built-in int() function, convert them to integers, so that we can do the integer math.

Notice what happens when we try to add "a" and "b." Instead we get string concatenation. The string "12" is concatenated with the string "5", not what we want. When you use the type() function to see what data type the variable "a" is, you can see that it's a string.

How would you permanently convert them to integers?


And the entire program, reading and converting to integers in one swoop.


Note how we use the return value of the raw_input() function as the argument for the int() conversion function, finally assigning that conversion to the variable "a".

No comments:

Post a Comment