Input and output

Introduction

Almost any interesting program has to get information from somewhere, and produce some sort of answers somewhere. These are called input and output. This sheet describes some of the ways Python handles input and output.

Some of the things in here require you to have done

from gasp.utils import read_number, read_yesorno

before they’ll work.

Input

Here are some useful functions that ask the user a question and wait for an answer. They all expect that the user will hit Enter after typing the answer.

input()

Reads a string from the keyboard. You don’t need to put quotation marks around it when you enter it.

input("What's your name? ")

Just like input(), but prints a message first.

These next two input functions are ones we wrote to make it easier to avoid errors (see Sheet E. You need to import them from the gasp.utils module (see Sheet M).

read_number()

Expects a number. If you type in something that isn’t a number, you’ll get told to try again. When you enter a number, it is returned to the part of your program that called read_number.

read_number('Enter a number: ')

The same, but prints that message before waiting for input. It’s usually better to use this version of read_number (perhaps with a different message, like 'How old are you?') so that the person using your program knows what’s required.

read_yesorno()

Expects yes, no, y or n, in either capitals or lowercase. It returns True when either yes or y is entered and False for no or n. A sample session in the interpreter might look like this:

>>> read_yesorno()
Yes or no? yes
True
>>> read_yesorno()
Yes or no? no
False
>>> read_yesorno()
Yes or no? What?
Please answer yes or no.
Yes or no? y
True
>>>
read_yesorno("Would you like another game? ")

Just like read_yesorno(), but prints a message first.

Output

The main thing you need to know about output is the print statement. It can print any object:

>>> x = [1, 2, 3]  # a list,
>>> y = 'zog'      # a string,
>>> z = 99         # a number,
>>> f = repr       # a function
>>> print(x, y, z, f)
[1, 2, 3] zog 99 <built-in function repr>

Notice that it puts spaces between the things it prints.

If you write two print statements, one after the other, you’ll see that the second starts printing on a fresh line rather than following on from the first. If that isn’t what you want, put end=' ' inside the first print:

print(123, end=' ')
print(456)

This will print 123 456 on a single line.