Добавил:
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
Gauld A.Learning to program (Python)_1.pdf
Скачиваний:
23
Добавлен:
23.08.2013
Размер:
1.34 Mб
Скачать

Conversing with the user

What will we cover?

How to prompt the user to enter data and how to read that data once it is entered. We will show how to read both numerical and string based data. Also we look at how to read data input as command line arguments.

So far our programs have only dealt with static data. Data that, if need be, we can examine before the program runs and thus write the program to suit. Most programs aren't like that. Most programs expect to be driven by a user, at least to the extent of being told what file to open, edit etc. Others prompt the user for data at critical points. Let's see how that can be done before we progress any further.

>>> print raw_input("Type something: ")

As you see raw_input simply displays the given prompt and captures whatever the user types in response. Print then displays that response. We could instead assign it to a variable:

resp = raw_input("What's your name? ") print "Hi, %s, nice to meet you" % resp

raw_input has a cousin called input. The difference is that raw_input collects the characters the user types and presents them as a string, whereas input collects them and tries to form them into a number. For example if the user types '1','2','3' then input will read those 3 characters and convert them into the number 123.

Let's use input to decide which multiplication table to print:

multiplier = input("Which multiplier do you want? Pick a number ") for j in range(1,13):

print "%d x %d = %d" % (j, multiplier, j * multiplier)

Unfortunately there's a big snag to using input. That's because input doesn't just evaluate numbers but rather treats any input as Python code and tries to execute it. Thus a knowledgable but malicious user could type in a Python command that deleted a file on your PC! For this reason it's better to stick to raw_input and convert the string into the data type you need using Python's built in conversion functions. This is actually pretty easy:

multiplier = int(raw_input("Which multiplier do you want? Pick a number "))

for j in range(1,13):

print "%d x %d = %d" % (j, multiplier, j * multiplier)

You see? We just wrapped the raw_input call in a call to int. It has the same effect as using input but is much safer. There are other conversion functions too so that you can convert to floats etc as well.

BASIC INPUT

In BASIC the INPUT statement reads input from the user thus:

INPUT "What multiplier do you want, pick a number ";M FOR J = 1 to 12

PRINT M "x" J "= " M*J NEXT J

46