3.4 Input and output

Computer programs generally involve interaction with the user. The is called input and output. Output involves printing things to the screen (and, as we shall see later, it also involves writing data to files, sending plots to a printer, etc). We have already seen one way of getting input--the input() function in Section 3.2. Functions will be discussed in more detail in Section 3.9, but for now we can use the input() function to get numbers (and only numbers) from the keyboard.

You can put a string between the parentheses of input() to give the user a prompt. Hence the example in Section 3.2 could be rewritten as follows:

    a = input("Please give a number: ") 
    b = input("And another: ")
    print "The sum of these numbers is:", a + b

[Note that in this mode of operation the input() function is actually doing output as well as input!]

The print command can print several things, which we separate with a comma, as above. If the print command is asked to print more than one thing, separated by commas, it separates them with a space. You can also concatenate (join) two strings using the + operator (note that no spaces are inserted between concatenated strings):

    >>> x = "Spanish Inquisition"
    >>> print "Nobody expects the" + x
    Nobody expects theSpanish Inquisition

input() can read in numbers (integers and floats) only. If you want to read in a string (a word or sentence for instance) from the keyboard, then you should use the raw_input() function; for example:

    >>> name = raw_input("Please tell me your name: ")

Copy the example in Section 3.2 into an empty module. Modify it so that it reads in three numbers and adds them up.

Further modify the program to ask the user for their name before inputting the three numbers. Then, instead of just outputting the sum, personalise the output message; eg. by first saying: ``name here are your results'' where name is their name. Think carefully about when to use input() and raw_input().