ВУЗ: Не указан

Категория: Не указан

Дисциплина: Не указана

Добавлен: 17.04.2021

Просмотров: 3744

Скачиваний: 3

ВНИМАНИЕ! Если данный файл нарушает Ваши авторские права, то обязательно сообщите нам.
background image

CHAPTER

FOUR

INPUT AND OUTPUT

A good relationship depends on good communications. In this chapter you learn how
to communicate with Python. Of course, communicating is a two-way street: input
and output. Generally, when you have Python perform some task, you need to feed it
information—input. When it is done with that task, it reports back to you the results of
its calculations—output.

There are two venues for input that concern us: the computer keyboard and the input data
file. Similarly, there are two venues for output: the computer screen and the output data
file. We start with input from the keyboard and output to the computer screen. Then we
deal with data file input and output—or “io.”

4.1 Keyboard input

Many computer programs need input from the user. In

Scripting Example 1

the program

needed the distance traveled as an input in order to determine the duration of the trip and
the cost of the gasoline. As you might like to use this same script to determine the cost of
several different trips, it would be useful if the program requested that input when it was
run from the IPython shell.

Python has a function called

raw_input

for getting input from the user and assigning

it a variable name. It has the form

strname

=

raw_input

(

"prompt to user"

)

When the

raw_input

statement is executed, it prints to the computer screen the text in

the quotes and waits for input from the user. The user types a string of characters and
presses the return key. The

raw_input

function then assigns that string to the variable

name on the right of the assignment operator

=

.

55


background image

Introduction to Python for Science, Release 0.9.23

Let’s try it out this snippet of code in the IPython shell.

In [1]:

distance

=

raw_input

(

"Input distance of trip in miles: "

)

Input distance of trip in miles:

Python prints out the string argument of the

raw_input

function and waits for a re-

sponse from you. Let’s go ahead and type

450

for “450 miles” and press return. Now

type the variable name

distance

to see its value

In [2]:

distance

Out[2]:

u’450’

The value of the

distance

is

450

as expected, but it is a string (the

u

stands for “uni-

code” which refers to the string coding system Python uses). Because we want to use

450

as a number and not a distance, we need to convert it from a string to a number. We

can do that with the

eval

function by writing

In [3]:

distance

=

eval

(distance)

In [4]:

distance

Out[4]:

450

The eval function has converted

distance

to an integer. This is fine and we are ready to

move on. However, we might prefer that

distance

be a float instead of an integer.

There are two ways to do this. We could assume the user is very smart and will type

450.

” instead of “

450

”, which will cause distance to be a float when

eval

does the

conversion. That is, the number 450 is dynamically typed to be a float or an integer
depending on whether or not the user uses a decimal point. Alternatively, we could use
the function

float

in place of

eval

, which would ensure that

distance

is a floating

point variable. Thus, our code would look like this (including the user response):

In [5]:

distance

=

raw_input

(

"Input distance of trip in miles: "

)

Input distance of trip in miles: 450

In [5]:

distance

Out[5]:

u’450’

In [7]:

distance

=

float

(distance)

In [8]:

distance

Out[8]:

450.0

Now let’s incorporate what we have learned into the code we wrote for

Scripting Example

1

56

Chapter 4. Input and Output


background image

Introduction to Python for Science, Release 0.9.23

1

# Calculates time, gallons of gas used, and cost of gasoline for

2

# a trip

3

4

distance

=

raw_input

(

"Input distance of trip in miles: "

)

5

distance

=

float

(distance)

6

7

mpg

=

30.

# car mileage

8

speed

=

60.

# average speed

9

costPerGallon

=

4.10

# price of gas

10

11

time

=

distance

/

speed

12

gallons

=

distance

/

mpg

13

cost

=

gallons

*

costPerGallon

Lines 4 and 5 can be combined into a single line, which is a little more efficient:

distance

=

float

(

raw_input

(

"Input distance of trip in miles: "

))

Whether you use

float

or

int

or

eval

depends on whether you want a float, an integer,

or a dynamically typed variable. In this program, it doesn’t matter.

Now you can simply run the program and then type

time

,

gallons

, and

cost

to view

the results of the calculations done by the program.

Before moving on to output, we note that sometimes you may want string input rather
that numerical input. For example, you might want the user to input their name, in which
case you would simply use the

raw_input

function without converting its output.

4.2 Screen output

It would be much more convenient if the program in the previous section would sim-
ply write its output to the computer screen, instead of requiring the user to type

time

,

gallons

, and

cost

to view the results. Fortunately, this can be accomplished very

simply using Python’s

print

function. For example, simply including the statement

print(time, gallons, cost)

after line 12, running the program would give the

following result:

In [1]:

run myTripIO

.

py

What is the distance of your trip in miles? 450

(7.5, 15.0, 61.49999999999999)

4.2. Screen output

57


background image

Introduction to Python for Science, Release 0.9.23

The program prints out the results as a tuple of time (in hours), gasoline used (in gallons),
and cost (in dollars). Of course, the program doesn’t give the user a clue as to which
quantity is which. The user has to know.

4.2.1 Formatting output with

str.format()

We can clean up the output of the example above and make it considerably more user
friendly. The program below demonstrates how to do this.

1

# Calculates time, gallons of gas used, and cost of gasoline for

2

# a trip

3

4

distance

=

float

(

raw_input

(

"Input distance of trip in miles: "

))

5

mpg

=

30.

# car mileage

6

speed

=

60.

# average speed

7

costPerGallon

=

4.10

# price of gas

8

9

time

=

distance

/

speed

10

gallons

=

distance

/

mpg

11

cost

=

gallons

*

costPerGallon

12

13

print

(

"

\n

Duration of trip = {0:0.1f} hours"

.

format(time))

14

print

(

"Gasoline used = {0:0.1f} gallons (@ {1:0.0f} mpg)"

15

.

format(gallons, mpg))

16

print

(

"Cost of gasoline = ${0:0.2f} (@ ${1:0.2f}/gallon)"

17

.

format(cost, costPerGallon))

Running this program, with the distance provided by the user, gives

In [9]:

run myTripNiceIO

.

py

What is the trip distance in miles? 450

Duration of trip = 7.5 hours

Gasoline used = 15.0 gallons (@ 30 mpg)

Cost of gasoline = $61.50 (@ $4.10/gallon)

Now the output is presented in a way that is immediately understandable to the user.
Moreover, the numerical output is formatted with an appropriate number of digits to the
right of the decimal point. For good measure, we also included the assumed mileage
(30 mpg) and the cost of the gasoline. All of this is controlled by the

str.format()

function within the

print

function.

The argument of the

print

function is of the form

str.format()

where

str

is a

58

Chapter 4. Input and Output


background image

Introduction to Python for Science, Release 0.9.23

string that contains text that is written to be the screen, as well as certain format specifiers
contained in curly braces

{}

. The

format

function contains the list of variables that are

to be printed.

• The

\n

at the start of the string in the

print

statement on line 12 in the newline

character. It creates the blank line before the output is printed.

• The positions of the curly braces determine where the variables in the

format

function at the end of the statement are printed.

• The format string inside the curly braces specifies how each variable in the

format

function is printed.

• The number before the colon in the format string specifies which variable in the list

in the

format

function is printed. Remember, Python is zero-indexed, so 0 means

the first variable is printed, 1 means the second variable,

etc

.

• The zero after the colon specifies the

minimum

number of spaces reserved for print-

ing out the variable in the format function. A zero means that only as many spaces
as needed will be used.

• The number after the period specifies the number of digits to the right of the decimal

point that will be printed:

1

for

time

and

gallons

and

2

for

cost

.

• The

f

specifies that a number with a fixed number of decimal points. If the

f

format

specifier is replaced with

e

, then the number is printed out in exponential format

(scientific notation).

In addition to

f

and

e

format types, there are two more that are commonly used:

d

for

integers (digits) and

s

for strings. There are, in fact, many more formatting possibili-

ties. Python has a whole “Format Specification Mini-Language” that is documented at

http://docs.python.org/library/string.html#formatspec

It’s very flexible but arcane. You

might find it simplest to look at the “Format examples” section further down the same
web page.

The program below illustrates most of the formatting you will need for writing a few
variables, be they strings, integers, or floats, to screen or to data files (which we discuss
in the next section).

string1

=

"How"

string2

=

"are you my friend?"

int1

=

34

int2

=

942885

float1

= -

3.0

float2

=

3.141592653589793e-14

print

(

’ ***’

)

4.2. Screen output

59