Chapter 6: Pointing to data

Example 6.1, Page No.98

In [4]:
num=100
sum=0.0123456789
text="C++ Fun"
print "Integer variable starts at",hex(id(num))
print "Double variable starts at",hex(id(sum))
print "String variable starts at",hex(id(text))
Integer variable starts at 0x126eb04
Double variable starts at 0x279b490
String variable starts at 0x2b7a160

Example 6.2, Page No.100

In [5]:
a=8
b=16
aPtr=id(a)
bPtr=id(b)
print "Address of pointers..."
print "aPtr:",hex(id(aPtr))
print "bPtr:",hex(id(bPtr))
print "Values in pointers..."
print "aPtr:",hex(aPtr)
print "bPtr:",hex(bPtr)
#As python does not support pointers values can't be displayed using * symbol
Address of pointers...
aPtr: 0x2808ac8
bPtr: 0x2808b1c
Values in pointers...
aPtr: 0x126e794
bPtr: 0x126e734

Example 6.3, Page No.102

In [8]:
nums={1,2,3,4,5,6,7,8,9,10}
ptr=id(nums)
#As python does not support concept of pointers we can not use pointer arithmetic to print numbers

Example 6.4, Page No.104

In [15]:
num=5
def writeOutput(value):
    print "Current Value: ",value
def computeTriple(value):
    global num
    num=num*3


writeOutput(num)
num=num+15
writeOutput(num)
computeTriple(num)
writeOutput(num)
Current Value:  5
Current Value:  20
Current Value:  60

Example 6.5, Page No.106

In [6]:
letters=['C','+','+',' ','F','u','n','\0']
text="C++ Fun"
term="Element"
lang="C++"
ap1=["Great ","Program ","Code "]
ap2=[lang,"is ","Fun"]
ap3=[ap2[0],ap2[1],ap1[0]]
ap4=[ap1[2],ap2[1],ap2[2]]
print "".join(letters)
print text
for i in range(0,3):
    print term,i," ",
    print ap1[i]," ",
    print ap2[i]," ",
    print ap3[i]," ",
    print ap4[i]," "
C++ Fun
C++ Fun
Element 0   Great    C++   C++   Code   
Element 1   Program    is    is    is   
Element 2   Code    Fun   Great    Fun  

Example 6.6, Page No.108

In [4]:
num=0
rNum=400
num=rNum
print "Value direct",num
print "Value via reference ",rNum

print "Address direct",hex(id(num))
print "Address via reference",hex(id(rNum))

rNum=rNum*2
num=rNum

print "Value direct",num
print "Value via reference ",rNum

#as python does not support pointers
Value direct 400
Value via reference  400
Address direct 0x27cd294
Address via reference 0x27cd294
Value direct 800
Value via reference  800

Example 6.7, Page No. 110

In [7]:
def writeOutput(value):
    print "Current Value: ",value

def computeTriple(value):
    value=value*3
    print "Current Value: ",value
    
num=5
ref=num
writeOutput(num)
num=num+15
writeOutput(num)
computeTriple(num)

#as python does not support pointers I dont have used pointer in this program
Current Value:  5
Current Value:  20
Current Value:  60

Example 6.8, Page No.113

In [10]:
def add(a,b):
    total=a+b
    print "total:",total

num=100
sum=500
rNum=num
ptr=num
print "Reference:",rNum
print "Pointer:",ptr
ptr=sum
print "Pointer now:",ptr
add(rNum,ptr)


#as python does not support pointers I dont have used pointer in this progaram
Reference: 100
Pointer: 100
Pointer now: 500
total: 600