Chapter 4 : Conditionals and recursion

example 4.1 page no :34

In [1]:
'''
example 4.1 page no :34
'''

def printParity (x):
    if (x%2 == 0):
        print "x is even" 
    else:
        print "x is odd" 

printParity (17)
x is odd

example 4.2 page no :36

In [2]:
'''
example 4.2 page no :36
'''
import math

def printLogarithm (x):
    if (x <= 0.0):
        print "Positive numbers only, please." 
        return;
    result = math.log(x);
    print "The log of x is " , result;

printLogarithm(-1)
printLogarithm(5)
Positive numbers only, please.
The log of x is  1.60943791243

example 4.3 page no : 37

In [3]:
'''
example 4.3 page no : 37
'''

def countdown (n):
    if (n == 0):
        print  "Blastoff!" 
    else:
        print n
        countdown (n-1)

countdown(5)
5
4
3
2
1
Blastoff!

example 4.4

In [4]:
'''
example  4.4
'''
import math
def printLogarithm(x):
    if (x <= 0.0):
        print "Positive numbers only, please." << endl;
        return;
    result = math.log(x)
    print "The log of x is " , result;

def countdown (n) :
    if (n == 0):
        print "Blastoff!"
    else:
        print n
        countdown (n-1);


countdown (3);
printLogarithm(10)
3
2
1
Blastoff!
The log of x is  2.30258509299
In [ ]: