#f. Output format
12 spaces between the first letter of “Name” and “Grade”
print("Name %12s" % "Grade") print("123456789012345678901234567890") >>> Name Grade 123456789012345678901234567890 >>>
The firs %10s is for “Name” right justified.
The second %10s is for “Grade” also right justified.
print("%10s%10s" % ("Name","Grade")) print("123456789012345678901234567890") >>> Name Grade 123456789012345678901234567890 >>>
The number 18129.06 has to fit in 10 spaces including the decimal
period, the two decimal digits after the period and right justified.
print("%10.2f" % (400.2 * 45.3)) print("123456789012345678901234567890") >>> 18129.06 123456789012345678901234567890 >>>
The two floating point numbers has to fit in 10 spaces and right justified.
print("%10.2f%10.2f" % (400.2 * 45.3, 55*123.2)) print("123456789012345678901234567890") >>> 18129.06 6776.00 123456789012345678901234567890 >>>
Let’s make use of the for loop, the range and the output formatting:
#g. Calculating compound interest principal = 1000.00 # starting principal rate = 0.5 # interest rate print ("Year %21s" % "Amount on deposit:") ## 1234123456789012345678901 ## Year Amount on deposit: for year in range (1,11): amount = principal * ( 1.0 + rate ) ** year # amount = principal * ( 1 + rate )^year print ("%4d%21.2f" % (year,amount)) # cool format to display a table ## %4d is for a number of 4 digits for variable year ## %21.2f is for a number of 21 positions: 18 digits, a decimal period and 2 decimal places #################################################################################### # %21.2f indicates that variable amount is printed as a float-point value with a # decimal point. # The column has a total field width of 21 character positions and two digits of # precision to the right of the decimal point; the total field width includes the # decimal point and the two digits to its right, hence 18 of the 21 positions appear # to the left of the decimal point. #################################################################################### print("1234123456789012345678.90") ## ##Year Amount on deposit: ## 1 1500.00 ## 2 2250.00 ## 3 3375.00 ## 4 5062.50 ## 5 7593.75 ## 6 11390.62 ## 7 17085.94 ## 8 25628.91 ## 9 38443.36 ## 10 57665.04 ##1234123456789012345678.90