$$ \newcommand{\tp}{\thinspace .} $$

This chapter is taken from the book A Primer on Scientific Programming with Python by H. P. Langtangen, 5th edition, Springer, 2016.

Asking questions and reading answers

One of the simplest ways of getting data into a program is to ask the user a question, let the user type in an answer, and then read the text in that answer into a variable in the program. These tasks are done by calling a function with name raw_input in Python 2 - the name is just input in Python 3.

Reading keyboard input

A simple problem involving the temperature conversion from Celsius to Fahrenheit constitutes our main example: \( F=\frac{9}{5}C + 32 \). The associated program with setting C explicitly in the program reads

C = 22
F = 9./5*C + 32
print F

We may ask the user a question C=? and wait for the user to enter a number. The program can then read this number and store it in a variable C. These actions are performed by the statement

C = raw_input('C=? ')
The raw_input function always returns the user input as a string object. That is, the variable C above refers to a string object. If we want to compute with this C, we must convert the string to a floating-point number: C = float(C). A complete program for reading C and computing the corresponding degrees in Fahrenheit now becomes

C = raw_input('C=? ')
C = float(C)
F = 9.0/5*C + 32
print F

In general, the raw_input function takes a string as argument, displays this string in the terminal window, waits until the user presses the Return key, and then returns a string object containing the sequence of characters that the user typed in.

The program above is stored in a file called c2f_qa.py (the qa part of the name reflects question and answer). We can run this program in several ways. The convention in this document is to indicate the execution by writing the program name only, but for a real execution you need to do more: write run before the program name in an interactive IPython session, or write python before the program name in a terminal session. Here is the execution of our sample program and the resulting dialog with the user:

c2f_qa.py
C=? 21
69.8
In this particular example, the raw_input function reads the characters 21 from the keyboard and returns the string '21', which we refer to by the variable C. Then we create a new float object by float(C) and let the name C refer to this float object, with value 21.

You should now try out Exercise 1: Make an interactive program, Exercise 6: Read input from the keyboard, and Exercise 9: Prompt the user for input to a formula to make sure you understand how raw_input behaves.