num = 1 flnum = 2.6 print("The integer is", num, "and the float is", flnum)prints
The integer is 1 and the float is 2.6A comma between two arguments prints a space. The keyword argument end=' ' puts a blank (or whatever string follows the = sign) at the end of the line and suppresses the skip to the next line:
print("Here is one print statement", end=’ ') print("And here is another")prints
Here is one print statement And here is anotherOne problem with unformatted printing is that you cannot avoid adding spaces before numbers. So, if you try to print “$1.39” with this:
print("$", 1.39)you get
$ 1.39(notice the unwanted space). To print this, you need a formatted print statement.
print("$%f" % (1.39))This prints
$1.390000The string immediately following the printf is the format string. It is printed as typed, except when a “%” is seen. The sequence of characters following it control how the next arguments are to be printed. “%f” means to print a floating point number. “%d” would mean to print an integer as a decimal number (“d” stands for “decimal”). The “%” after the string says that a tuple containing the arguments for the printing follow.1 One problem with the above—too many decimal places. Let’s restrict it to 2 decimal places by saying instead
print("$%.2f" % (1.39))This prints
$1.39The “%f” says to print the number as a floating point number. The “.2” between the “%” and “f” means to print 2 digits after the decimal point. As another example, if you want to print the value of π to 7 decimal places, say:
import math print("The value of pi is %.7f" % (math.pi))You get
The value of pi is 3.1415927Now suppose you want to print a table of numbers. You might say:
for i in range(1, 5): print("%.2f" % (math.pi * i))You get this:2
3.14 6.28 9.42 12.57That doesn’t line up too well! We really want the numbers to the left of the decimal point to take up the same amount of room so the decimal points line up. So, we want to line the numbers up to the right. To do this, we first figure out how many characters (including the decimal point) we want the numbers to take up. That's 5 (because 12.57 has 5 characters and the rest have 4). So, we use the following format string:
"%5.2f"When you make this change to the above print, you get:
3.14 6.28 9.42 12.57Now let’s say we want to print several arguments. You do it this way:
print "%d + %d = %d" % (2, 2, 2 + 2)gives
2 + 2 = 4You can get very fancy:
print(’%(language)s has %(#)03d quote types.' % {"#":2, 'language':"Python"})gives
Python has 002 quote types.
x = "2 * %f = %f" % (math.pi, 2*math.pi) print xand you will see
2 * 3.141593 = 6.283185
ECS 10, Basic Concepts of Computing Fall Quarter 2012 |