Chapter 3: Formatted I/O

Example on Page 38

In [3]:
#variable declaration
i=10
j=20
x=43.2892
y=5527.0
#print statement
print "i = %d, j = %d, x = %f, y = %f" % (i,j,x,y)
i = 10, j = 20, x = 43.289200, y = 5527.000000

Example tprintf.c on Page 40

In [6]:
def main():
    #variable declaration
    i=40
    x=839.21
    
    #formatted printing
    print "|%d|%5d|%-5d|%5.3d|" % (i,i,i,i)
    print "|%10.3f|%10.3e|%-10g|" % (x,x,x)
    
if  __name__=='__main__':
    main()
|40|   40|40   |  040|
|   839.210| 8.392e+02|839.21    |

Example addfrac.c on Page 46

In [4]:
def main():

    print " Enter first fraction: ",
    #accepting numerator and denominator separated by '/'
    num1,denom1=map(int,raw_input().split('/')) 
    print "Enter second fraction: ",
    num2,denom2=map(int,raw_input().split('/'))
    #adding the fractions
    result_num = num1*denom2 + num2*denom1 
    result_denom = denom1*denom2
    print "The sum is %d/%d" % (result_num,result_denom)

if  __name__=='__main__':
    main()
Enter first fraction: 5/6
 Enter second fraction: 3/4
 The sum is 38/24
In [ ]: