Chapter 7 Standard C Library Functions and Standard Header Files

Program Source Code 7.1, page no: 179

In [1]:
def lineno():                      #to print lineno
   return inspect.currentframe().f_back.f_lineno
x=10
print 'First call to assert '    #assert
assert(x==10)
print 'Second call to assert '

#assert(x!=10)  assertion failed will be seen
#print 'Done '
First call to assert 
Second call to assert 

Program Source Code 7.2, page no: 181

In [2]:
SIZE=3

str=['ab12cd','34ef56','gh78jk']     #str array declared

NoofAlphabets=[0,0,0]
temp=0
for i in range(SIZE):
    NoofAlphabets[i]=0

    temp=str[i]
    for j in range(len(temp)):
       if temp[j].isalpha():               #isalpha to find if its alphabet
            NoofAlphabets[i]=NoofAlphabets[i]+1
    print 'Number of alphabets in string : ',str[i],
    print 'is',NoofAlphabets[i]
Number of alphabets in string :  ab12cd is 4
Number of alphabets in string :  34ef56 is 2
Number of alphabets in string :  gh78jk is 4

Program Source Code 7.3, page no: 185

In [3]:
import math

PI=3.1415926535

x=PI/2.0
y=4.5
z=2.30258093
n=0
print 'sine of PI/2 is',
print int(math.sin(x))
print 'cosine of PI/2 is',
print math.cos(x)
print 'exponent of %.5f'%z,'is',
print math.exp(z)

#frexp() take single argument and return a pair of values,rather than returning their second return value through output parameters
#therefore no such thing occurs in python
sine of PI/2 is 1
cosine of PI/2 is 4.48965921698e-11
exponent of 2.30258 is 9.99995837015

Program Source Code 7.4, page no: 188

In [4]:
def sum(first):        #function declared to compute the sum
    j=1
    i=first[0]
    s=0
    while not i==-1:
        s+=i
        i=first[j]
        j+=1
    return s
        
    
print 'sum is: ',sum([2,3,4,-1])        #function called
print 'sum is: ',sum([5,7,9,11,-1])
print 'sum is: ',sum([-1])
sum is:  9
sum is:  32
sum is:  0
In [ ]: