Chapter 9: Processing macros

Example 9.1, Page No.153

In [1]:
print "This is a simple test program"
This is a simple test program

Example 9.2, Page No.154

In [7]:
BOOK="C++ Programming in easy steps"
NUM=200
RULE="*****************************"
print RULE
print BOOK
print RULE
print "NUM is:",NUM
print "Double NUM:",NUM*2
*****************************
C++ Programming in easy steps
*****************************
NUM is: 200
Double NUM: 400

Example 9.3, Page No.156

In [26]:
if not 'BOOK' in locals():
    BOOK="C++ Programming in easy steps"

print BOOK,
if not 'AUTHOR' in locals():
    AUTHOR="Mike McGrath"
print " by ",AUTHOR
if not 'BOOK' in locals():
    BOOK=""
if 'BOOK' in locals():
    BOOK="Linux in easy steps"

print BOOK," by ",AUTHOR
Linux in easy steps  by  Mike McGrath
Linux in easy steps  by  Mike McGrath

Example 9.4, Page No.159

In [32]:
import platform
plat=platform.system()
print plat," system"
if plat=="Windows":
    print "Performing Windows-only tasks"
else:
    print "Performing Linux-only tasks"
Windows  system
Performing Windows-only tasks

Example 9.5, Page No.160

In [34]:
def add(x,y):
    return x+y
def triple(x):
    return (add(x,add(x,x)))
print "9 + 3 = ",add(9,3)
print "9 x 3 = ",triple(9)
9 + 3 =  12
9 x 3 =  27

Example 9.6, Page No.162

In [35]:
def SQUARE(n):
    return n*n
def CUBE(n):
    return n*n*n
num=5
print "Macro SQUARE:",SQUARE(num)
print "inline square:",SQUARE(num)
print "Macro CUBE:",CUBE(num)
print "inline CUBE:",CUBE(num)
Macro SQUARE: 25
inline square: 25
Macro CUBE: 125
inline CUBE: 125

Example 9.7, Page No.164

In [36]:
def LINEOUT(str):
    print str
def GLUEOUT(a,b):
    print a," ",b
longer="They carried a net "
line="and their hearts "
LINEOUT("In a bowl to sea went wise men three")
LINEOUT("On a brilliant night in      June")
GLUEOUT(longer,line)
LINEOUT("On fishing up the moon.")
In a bowl to sea went wise men three
On a brilliant night in      June
They carried a net    and their hearts 
On fishing up the moon.

Example 9.8, Page No.166

In [10]:
DEBUG=0
if DEBUG == 1:
    def ASSERT(expr):
        print expr, "...", num
        if expr != True:
            print "Fails in  file: "# There is no concept of line in python
            print "at line"# There is no concept of line in python
        else:
            print "Succeeds"
elif DEBUG == 0:
    def ASSERT(expr):
        print "Number is ",num
num = 9
ASSERT(num < 10)
num = num + num
ASSERT(num < 10)
Number is  9
Number is  18