Sie sind auf Seite 1von 4

1.9.

Input and Output Problem Solving with Algorithms and Data


6/11/17,
S... 2:45 PM

1.9. Input and Output


We of ten have a need to interact w ith users, either to get data or to provide some sort of result. Most
programs today use a dialog box as a w ay of asking the user to provide some type of input. While
Python does have a w ay to create dialog boxes, there is a much simpler f unction that w e can use.
Python provides us w ith a f unction that allow s us to ask a user to enter some data and returns a
ref erence to the data in the f orm of a string. The f unction is called input .

Pythons input f unction takes a single parameter that is a string. This string is of ten called the prom pt
because it contains some helpf ul text prompting the user to enter something. For example, you might call
input as f ollow s:

aName = input('Please enter your name: ')

Now w hatever the user types af ter the prompt w ill be stored in the aName variable. Using the input
f unction, w e can easily w rite instructions that w ill prompt the user to enter data and then incorporate
that data into f urther processing. For example, in the f ollow ing tw o statements, the f irst asks the user
f or their name and the second prints the result of some simple processing based on the string that is
provided.

Run Load History Show CodeLens

1 aName = input("Please enter your name ")


2 print("Your name in all capitals is",aName.upper(),
3 "and has length", len(aName))
4

ActiveCode: 1 The input Function Returns a String (strstuff )

It is important to note that the value returned f rom the input f unction w ill be a string representing the
exact characters that w ere entered af ter the prompt. If you w ant this string interpreted as another
type, you must provide the type conversion explicitly. In the statements below , the string that is entered
by the user is converted to a f loat so that it can be used in f urther arithmetic processing.

sradius = input("Please enter the radius of the circle ")


radius = float(sradius)
diameter = 2 * radius

1.9.1. String Formatting


We have already seen that the print f unction provides a very simple w ay to output values f rom a
Python program. print takes zero or more parameters and displays them using a single blank as the
def ault separator. It is possible to change the separator character by setting the sep argument. In
addition, each print ends w ith a new line character by def ault. This behavior can be changed by setting

1 of 4
1.9. Input and Output Problem Solving with Algorithms and Data
6/11/17,
S... 2:45 PM

the end argument. These variations are show n in the f ollow ing session:

>>> print("Hello")
Hello
>>> print("Hello","World")
Hello World
>>> print("Hello","World", sep="***")
Hello***World
>>> print("Hello","World", end="***")
Hello World***>>>

It is of ten usef ul to have more control over the look of your output. Fortunately, Python provides us w ith
an alternative called form atte d s trings . A f ormatted string is a template in w hich w ords or spaces
that w ill remain constant are combined w ith placeholders f or variables that w ill be inserted into the
string. For example, the statement

print(aName, "is", age, "years old.")

contains the w ords is and years old , but the name and the age w ill change depending on the
variable values at the time of execution. Using a f ormatted string, w e w rite the previous statement as

print("%s is %d years old." % (aName, age))

This simple example illustrates a new string expression. The % operator is a string operator called the
form at ope rator. The lef t side of the expression holds the template or f ormat string, and the right side
holds a collection of values that w ill be substituted into the f ormat string. Note that the number of values
in the collection on the right side corresponds w ith the number of % characters in the f ormat string.
Values are takenin order, lef t to rightf rom the collection and inserted into the f ormat string.

Lets look at both sides of this f ormatting expression in more detail. The f ormat string may contain one or
more conversion specif ications. A conversion character tells the f ormat operator w hat type of value is
going to be inserted into that position in the string. In the example above, the %s specif ies a string,
w hile the %d specif ies an integer. Other possible type specif ications include i , u , f , e , g , c , or % .
Table 9 summarizes all of the various type specif ications.

Characte r Output Form at

d, i Integer

u Unsigned integer

f Floating point as m.ddddd

e Floating point as m.ddddde+/-xx

E Floating point as m.dddddE+/-xx

g Use %e f or exponents less than 4 or greater than +5, otherw ise use %f

2 of 4
1.9. Input and Output Problem Solving with Algorithms and Data
6/11/17,
S... 2:45 PM

Characte r Output Form at

c Single character

s String, or any Python data object that can be converted to a string by using the
str f unction.

% Insert a literal % character

In addition to the f ormat character, you can also include a f ormat modif ier betw een the % and the
f ormat character. Format modif iers may be used to lef t-justif y or right-justif iy the value w ith a specif ied
f ield w idth. Modif iers can also be used to specif y the f ield w idth along w ith a number of digits af ter the
decimal point. Table 10 explains these f ormat modif iers

M odifie r Exam ple De s cription

number %20d Put the value in a f ield w idth of 20

- %-20d Put the value in a f ield 20 characters w ide, lef t-justif ied

+ %+20d Put the value in a f ield 20 characters w ide, right-justif ied

0 %020d Put the value in a f ield 20 characters w ide, f ill in w ith leading zeros.

. %20.2f Put the value in a f ield 20 characters w ide w ith 2 characters to the
right of the decimal point.

(name) %(name)d Get the value f rom the supplied dictionary using name as the key.

The right side of the f ormat operator is a collection of values that w ill be inserted into the f ormat string.
The collection w ill be either a tuple or a dictionary. If the collection is a tuple, the values are inserted in
order of position. That is, the f irst element in the tuple corresponds to the f irst f ormat character in the
f ormat string. If the collection is a dictionary, the values are inserted according to their keys. In this case
all f ormat characters must use the (name) modif ier to specif y the name of the key.

>>> price = 24
>>> item = "banana"
>>> print("The %s costs %d cents"%(item,price))
The banana costs 24 cents
>>> print("The %+10s costs %5.2f cents"%(item,price))
The banana costs 24.00 cents
>>> print("The %+10s costs %10.2f cents"%(item,price))
The banana costs 24.00 cents
>>> itemdict = {"item":"banana","cost":24}
>>> print("The %(item)s costs %(cost)7.1f cents"%itemdict)
The banana costs 24.0 cents
>>>

3 of 4
1.9. Input and Output Problem Solving with Algorithms and Data
6/11/17,
S... 2:45 PM

In addition to f ormat strings that use f ormat characters and f ormat modif iers, Python strings also include
a format method that can be used in conjunction w ith a new Formatter class to implement complex
string f ormatting. More about these f eatures can be f ound in the Python library ref erence manual.

4 of 4

Das könnte Ihnen auch gefallen