Log in / Register
Home arrow Computer Science arrow Python Programming Fundamentals
< Prev   CONTENTS   Next >

1.15 Getting Input

To get input from the user you can use the input function. When the input function is called the program stops running the program, prompts the user to enter something at the keyboard by printing a string called the prompt to the screen, and then waits for the user to press the Enter key. The user types a string of characters and presses enter. Then the input function returns that string and Python continues running the program by executing the next statement after the input statement.

Example 1.6 Consider this short program.

name = i n p u t ("Please enter your name:")

p r i n t ("The name you entered was", name)

The input function prints the prompt “Please enter your name:” to the screen and waits for the user to enter input in the Python Shell window. The program does not continue executing until you have provided the input requested. When the user enters some characters and presses enter, Python takes what they typed before pressing enter and stores it in the variable called name in this case. The type of value read by Python is always a string. If we want to convert it to an integer or some other type of value, then we need to use a conversion operator. For instance, if we want to get an int from the user, we must use the int conversion operator.

Practice 1.13 Assume that we want to pause our program to display someoutput and we want to let the user press some key to continue.We want to print“press any key to continue. . .” to the screen. Can we use the input function toimplement this? If so, how would you write the input statement? If not, whycan't you use input?

Example 1.7 This code prompts the user to enter their age. The string thatwas returned by input is first converted to an integer and then stored in thevariable called age. Then the age variable can be added to another integer. Itis important to remember that input always returns a string. If some other typeof data is desired, then the appropriate type conversion must be applied to thestring.

age = i n t ( i n p u t ("Please enter your age:"))

olderAge = age + 1

p r i n t ("Next year you will be", olderAge)

1.16 Formatting Output

In this chapter just about every fragment of code prints something. When a value is printed, it appears on the console. The location of the console can vary depending on how you run a program. If a program is run from within the Wing IDE, the console is the Python Shell window in the IDE. If the program is debugged from within Wing IDE 101, the output appears in the Debug I/O window.

When printing, we may print as many items as we like on one line by separating each item by a comma. Each time a comma appears between items in a print statement, a space appears in the output.

Example 1.8 Here is some code that prints a few values to the screen.

name = "Sophus"

p r i n t (name ,"how are you doing?")

p r i n t ("I hope that ,", name , "is feeling well today.")

The output from this is:

Sophus how are your doing?

I hope that Sophus i s feeling well today.

To print the contents of variables without spaces appearing between the items, the variables must be converted to strings and string concatenation can be used. The + operator adds numbers together, but it also concatenates strings. For the correct + operator to be called, each item must first be converted to a string before concatenation

can be performed.

Example 1.9 Assume that we ask the user to enter two floating point numbers,x and y, and we wish to print the result of raising x to the yth power.We wouldlike the output to look like this.

Please enter a number: 4.5

Please enter an exponent: 3.2

4.5^3.2 = 123.10623351

Here is a program that will produce that output, with no spaces in the exponentiationexpression. NOTE: The caret symbol (i.e.ˆ) is not the Python symbolfor exponentiation.

1 base = f l o a t ( i n p u t ("Please enter a number:"))

2 exp = f l o a t ( i n p u t ("Please enter an exponent:"))

3 answer = base ** exp

4 p r i n t ( s t r (base) + "^" + s t r (exp), "=", answer)

In Example 1.9, line 4 of the program prints three items to the console. The last two items are the = and the value that the answer variable references. The first item in the print statement is the result of concatenating str(base), the caret, and str(exp).Both base and exp must be converted to strings first, then string concatenation will be performed by the + operator because the operands on either side of the + are both strings.

Practice 1.14 The sum of the first n positive integers can be computed by theformula

sum(1..n) = 1 + 2 + 3 + 4 + •• •+n = n(n + 1)/2

Write a short Python program that computes the sum of the first 100 positiveintegers and prints it to the screen in the format shown below. Use variablesto represent the 1, the 100, and the result of the computation. Your programmust compute the 5050 value. You cannot just print the result to the screen.You must compute it first from the 100.

sum (1..100)=5050

For advanced control of the format of printing we can use string formatting. String formatting was first used in the C language printf function back in the 1970s. It's an idea that has been around a long time, but is still useful. The idea is that we place formatting instructions in a string and then tell Python to replace the formatting instructions with the actual values. This is best described with an example.

Example 1.10 Assume we wish to re-implement the program in Example 1.9.However, in this version of the program, if the user enters more than twodecimal places for either number we wish to round the numbers to two digitsof precision when they are printed to the console. Assume we wish to roundthe answer to four decimal places when displayed. The following code will dothis

.1 base = f l o a t ( i n p u t ("Please enter a number:"))

2 exp = f l o a t ( i n p u t ("Please enter an exponent:"))

3 answer = base ** exp

4 p r i n t ("%1.2f^%1.2f = %1.4f"%(base ,exp ,answer ))

Running this program produces the following output.

Please enter a number: 4.666666667

Please enter an exponent: 3.3333333333

4.67^3.33 = 169.8332

Line 4 in Example 1.10 prints the result of formatting a string. To use Python formatting, a format string must be written first, followed by a percent sign, followed by the replacement values. If there is more than one replacement value, they must be written in parentheses. Each time a % appears inside the format string it is replaced by one of the values that appear after the format string. How a value is formatted when it is placed in the format string is controlled by the format specifier. Figure 1.20





% wd

Places an integer in a field of width w if specified. %2d would place

an integer in a field of width 2. w may be omitted.


% wx

Format the integer in hexadecimal Put it in a field of width w if spec-

ified. w may be omitted.


% wo

Format the integer in octal. Put it in a field of width w if specified. w

may be omitted.


% w.df

Format a floating point number with total width w (including the dec-

imal point) and with d digits after the decimal point. Displaying the entire number include the d digits takes precedence over displaying in a field of w characters should w not be big enough. w and d may be omitted.



Format a floating point number using scientific notation with d digits

of precision and w field width. Scientific notation uses an exponent of 10 to move the decimal point so only one digit appears to the left of the decimal point. w and d may be omitted.


% ws

Place a string in a field of width w. w may be omitted.


Include a %sign in the formatted string.

Fig. 1.20 Format specifiers

contains some specifiers for common types of data in Python. Every format specifier may include an optional width field. If specified, the width field specifies the actual width of the replaced data. If the width of the data being inserted into the format string exceeds the allotted width, the entire field is included anyway, stretching the width of the formatted string. String formatting can be very useful when generating a printed report of some data.

Practice 1.15 Re-do Practice Problem 1.14 using format specifiers whenprinting instead of converting each item to a string. The goal is for the outputto look exactly the same.

sum (1..100)=5050

Found a mistake? Please highlight the word and press Shift + Enter  
< Prev   CONTENTS   Next >
Business & Finance
Computer Science
Language & Literature
Political science