Chapter 5: Functions

Example 5.1, Page Number: 163

In [1]:
def starline():                  #function declarator
    for j in range(25):          #function body
        print '*', 
    print
    
    
starline()                       #call to function
print 'Data type   Range'
starline()                       #call to function
print 'Char        -128 to 127'
print 'short       -32,768 to 32,767'
print 'int         System dependent'
print 'long        -2,147,483,648 to 2,147,483,647'
starline()                       #call to function
* * * * * * * * * * * * * * * * * * * * * * * * *
Data type   Range
* * * * * * * * * * * * * * * * * * * * * * * * *
Char        -128 to 127
short       -32,768 to 32,767
int         System dependent
long        -2,147,483,648 to 2,147,483,647
* * * * * * * * * * * * * * * * * * * * * * * * *

Example 5.2, Page Number: 167

In [2]:
                #function definition
def starline():
    for j in range(25):
        print '*',
    print
    
    
starline()                          #call to function
print 'Data type   Range'
starline()                          #call to function
print 'Char        -128 to 127'
print 'short       -32,768 to 32,767'
print 'int         System dependent'
print 'long        -2,147,483,648 to 2,147,483,647'
starline()                          #call to function
* * * * * * * * * * * * * * * * * * * * * * * * *
Data type   Range
* * * * * * * * * * * * * * * * * * * * * * * * *
Char        -128 to 127
short       -32,768 to 32,767
int         System dependent
long        -2,147,483,648 to 2,147,483,647
* * * * * * * * * * * * * * * * * * * * * * * * *

Example 5.3, Page Number: 168

In [3]:
def repchar(ch,n):                    #function declarator
    for j in range(n):                #function body
        print ch,
    print
   
    
repchar('-',22)                       #call to function
print 'Data type   Range'
repchar('=',12)                       #call to function
print 'Char        -128 to 127'
print 'short       -32,768 to 32,767'
print 'int         System dependent'
print 'long        -2,147,483,648 to 2,147,483,647'
repchar('-',22)                       #call to function
- - - - - - - - - - - - - - - - - - - - - -
Data type   Range
= = = = = = = = = = = =
Char        -128 to 127
short       -32,768 to 32,767
int         System dependent
long        -2,147,483,648 to 2,147,483,647
- - - - - - - - - - - - - - - - - - - - - -

Example 5.4, Page Number: 169

In [4]:
def repchar(ch,n):                    #function declarator
    for j in range(n):                #function body
        print ch,
    print
    
    
chin = raw_input("Enter a character: ")             #get character from user

nin = input("Enter number of times to repeat it: ")  #get repetition

repchar(chin,nin)                       #call to function
Enter a character: +
Enter number of times to repeat it: 20
+ + + + + + + + + + + + + + + + + + + +

Example 5.5, Page Number: 172

In [5]:
class Distance:                #Distance class
    feet = None
    inches = None

                               #function for display distance
def engldisp(dd):              #parameter dd of type Distance
    print dd.feet,'\' -',dd.inches,'\"',
    
                        #define two lengths
d1 = Distance()
d2 = Distance()

                        #get length d1 from user
d1.feet = input("Enter feet: ")
d1.inches = input("Enter inches: ")

                        #get length d2 from user
d2.feet = input("\nEnter feet: ")
d2.inches = input("Enter inches: ")

print '\nd1 =',          #display length 1
engldisp(d1)

print '\nd2 =',          #display length 2
engldisp(d2)
Enter feet: 6
Enter inches: 4

Enter feet: 5
Enter inches: 4.25

d1 = 6 ' - 4 " 
d2 = 5 ' - 4.25 "

Example 5.6, Page Number: 174

In [6]:
from turtle import Turtle,setup,done       #importing turtles library

class circle:          #defining circle class
    xCo = None
    yCo = None
    radius = None
    fillcolor = None

                        #draw circle
def circ_draw(c):
    setup()
    turtle = Turtle()
    turtle.begin_fill()
    turtle.color(c.fillcolor)
    turtle.up()
    turtle.goto(c.xCo,c.yCo)
    turtle.down()
    turtle.circle(c.radius)
    turtle.end_fill()
    turtle.hideturtle()
    done()
    
    
    
                    #create circles
c1 = circle()
c2 = circle()
c3 = circle()
        
                    #initialize the values of each circle
c1.xCo = 15
c1.yCo = 7
c1.radius = 5
c1.fillcolor = "Blue"

c2.xCo = 41
c2.yCo = 12
c2.radius = 7
c2.fillcolor = "Red"

c3.xCo = 65
c3.yCo = 18
c3.radius = 4
c3.fillcolor = "Green"

                    #draw circle
circ_draw(c1)
circ_draw(c2)
circ_draw(c3)

Example 5.7, Page Number: 176

In [7]:
def lbstokg(pounds):                #function for converting pounds to kilograms
    kilograms = 0.453592 * pounds
    return kilograms

lbs = input("Enter your weight in pounds: ")         #get the weight from user

kgs = lbstokg(lbs)          #function call 

print 'Your weight in kilogram is',kgs,'\n'         #display weight from pounds to kilogram
Enter your weight in pounds: 182
Your weight in kilogram is 82.553744 

Example 5.8, Page Number: 179

In [8]:
def lbstokg(pounds):                #function for converting pounds to kilogram
    return 0.453592 * pounds

lbs = input("Enter your weight in pounds: ")         #get the weight from user

print 'Your weight in kilogram is',lbstokg(lbs),'\n'   #call function an display weight
Enter your weight in pounds: 182
Your weight in kilogram is 82.553744 

Example 5.9, Page Number: 180

In [9]:
class Distance:                 #Distance class
    feet = None
    inches = None

def addeng1(dd1,dd2):          #function for add two lengths
    
    dd3 = Distance()           #define a new structure for sum
    
    dd3.inches = dd1.inches + dd2.inches        #add the inches
    dd3.feet = 0

    if dd3.inches>=12.0:       #if inches >= 12.0
        dd3.inches -= 12.0     #then decrease inches by 12,0
        dd3.feet += 1          #and increase feet by 1
        
    dd3.feet += dd1.feet + dd2.feet        #add feet
    
    return dd3                 #return structure
  
    
def engldisp(dd):              #display the length
    print dd.feet,'\' -',dd.inches,'\"',
    
    
    
    
                    #define three lengths
d1 = Distance()
d2 = Distance()
d3 = Distance()

                        #get length d1 from user
d1.feet = input("Enter feet: ")
d1.inches = input("Enter inches: ")

                        #get length d2 from user
d2.feet = input("\nEnter feet: ")
d2.inches = input("Enter inches: ")
                
d3 = addeng1(d1,d2)        #d3 is sum of d1 and d2

print '\n',                #display all lengths
engldisp(d1); print ' + ',
engldisp(d2); print ' = ',
engldisp(d3); print '\n'
Enter feet: 4
Enter inches: 5.5

Enter feet: 5
Enter inches: 6.5

4 ' - 5.5 "  +  5 ' - 6.5 "  =  10 ' - 0.0 " 

Example 5.10, Page Number: 182

In [10]:
def intfrac(n):                    #function for finding the integer and fractional part of real number
    temp = n
    intp = int(temp)          #convert to int
    fracp = n - intp          #subtract integer part to get fractional part
    return intp,fracp


while True:
    
    number = input("Enter a real number: ")            #get number from user
    
    intpart,fracpart = intfrac(number)                 #function call
    
    if number == 0.0:        #exit loop when number is 0.0
        break
        
    print 'Integer part is',intpart,', fraction part is',fracpart,'\n'       #print integer and fractional part
Enter a real number: 99.44
Integer part is 99 , fraction part is 0.44 

Enter a real number: 0

Example 5.11, Page Number: 185

In [11]:
def order(numb1,numb2):        #orders of two numbers
    
    if numb1>numb2:            #if 1st larger than 2nd
        temp = numb1           #swap them
        numb1 = numb2
        numb2 = temp
        
    return numb1,numb2



n1 = 99       #this pair not ordered
n2 = 11

n3 = 22       #this pair ordered
n4 = 88

n1,n2 = order(n1,n2)           #order each pair of numbers
n3,n4 = order(n3,n4)

print 'n1 =',n1             #print out all numbers
print 'n2 =',n2
print 'n3 =',n3
print 'n4 =',n4
n1 = 11
n2 = 99
n3 = 22
n4 = 88

Example 5.12, Page Number: 186

In [12]:
class Distance:                 #class Distance
    feet = None
    inches = None
    
def scale(dd,factor):           #Scales value of type Distance by factor
    inches = (dd.feet*12 + dd.inches) * factor
    dd.feet = int(inches/12)
    dd.inches = inches - dd.feet * 12
    return dd

def engldisp(dd):               #dispaly length
    print dd.feet,'\' -',dd.inches,'\"'

    
    
d1 = Distance()           #initialize d1
d1.feet = 12
d1.inches = 6.5

d2 = Distance()           #initialize d2
d2.feet = 10
d2.inches = 5.5

print 'd1 =', ; engldisp(d1)          #display old d1 and d2
print 'd2 =', ; engldisp(d2)

d1 = scale(d1,0.5)              #scale d1 and d2
d2 = scale(d2,0.25)

print 'd1 =', ; engldisp(d1)          #display new d1 and d2
print 'd2 =', ; engldisp(d2)
d1 = 12 ' - 6.5 "
d2 = 10 ' - 5.5 "
d1 = 6 ' - 3.25 "
d2 = 2 ' - 7.375 "

Example 5.13, Page Number: 189

In [13]:
def repchar(ch=None,n=None):           #display specified character
    
    if ch == None:
        for j in range(45):            #display 45 asterisks
            print '*',
        print ''
        
    elif n == None:
        for j in range(45):           #display 45 specified character
            print ch,
        print ''
        
    else:
        for j in range(n):            #display specified number of copies of specified character 
            print ch,
        print ''
        
        
repchar()                    #call functions
repchar('=')
repchar('+',30)
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * 
= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = 
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 

Example 5.14, Page Number: 191

In [14]:
class Distance:                #Distance class
    feet = None
    inches = None

    
#function overloading
def engldisp(dd):              
    
    if isinstance(dd,float):       #if dd is float type
        feet = int(dd/12)
        inches = dd - feet*12
        print feet,'\' -',inches,'\"',
        
    else:                           #if parameter dd of type Distance
        print dd.feet,'\' -',dd.inches,'\"',
        
        
        
d1 = Distance()                          #distance of type Distance
d1.feet = input("Enter feet: ")          #get d1 from user
d1.inches = input("Enter inches: ")

d2 = input("\nEnter entire distance in inches: ")        #distance of type float

print '\nd1 =',           #display length d1
engldisp(d1)

print '\nd2 =',         #display length d2
engldisp(d2)
Enter feet: 5
Enter inches: 10.5

Enter entire distance in inches: 76.5

d1 = 5 ' - 10.5 " 
d2 = 6 ' - 4.5 "

Example 5.15, Page Number: 193

In [15]:
def factfunc(n):               #calls itself to calculate factorials
    
    if n>1:
        return n * factfunc(n-1)
    else:
        return 1
    
    
n = input("Enter an integer: ")             #get number from user

fact = factfunc(n)                          #function call for factorial
print 'Factorial of',n,'is',fact,'\n'       #dsplay factorial
Enter an integer: 5
Factorial of 5 is 120 

Example 5.16, Page Number: 197

In [16]:
#inline function
lbstokg = lambda pounds: 0.453592 * pounds             #converts pounds to kilogram

lbs = input("Enter your weight in pounds: ")           #get weight from user
print 'Your weight in kilogram is',lbstokg(lbs)        #convert it and display
Enter your weight in pounds: 182
Your weight in kilogram is 82.553744

Example 5.17, Page Number: 198

In [17]:
def repchar(ch='*',n=45):        #function with default arguments
    for j in range(n):           #loops n times
        print ch,                #print ch
    print
                       
        
repchar()                #prints 45 asterisks
repchar('=')             #prints 45 equal sign
repchar('+',30)          #prints 30 plus sign
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +

Example 5.18, Page Number: 202

In [18]:
ch = 'a'

def getachar():            #function for accesses text line
    global ch
    ch = raw_input()

def putachar():        #function for display text line
    global ch
    print ch
    
    
getachar()         #functions call
putachar()
I'm typing in this line if text
I'm typing in this line if text

Example 5.19, Page Number: 204

In [19]:
total = 0           #works as static variables
count = 0

def getavg(newdata):      #function for finds average of old and new data
    global total
    global count
    
    count += 1             #increment count
    total += newdata       #add new data to total
    
    return total / count      #return the new average



data = 1

while(data != 0):
    data = input("Enter a number: ")       #get data from user
    avg = getavg(data)                     #find out average each time
    print 'new average is',avg             #print average
Enter a number: 10
new average is 10
Enter a number: 20
new average is 15
Enter a number: 30
new average is 20
Enter a number: 0
new average is 15

Example 5.20, Page Number: 206

In [20]:
x = None                #global variable

def setx():             #returns the value to be modified
    global x
    return x


x = 92                 #set x to a value

print 'x =',setx()      #and print x using functon call
x = 92

Example 5.21, Page Number: 208

In [21]:
def aFunc(a,b):        #functon for modify the arguments
    a = 107
    b = 111
    return a,b


alpha = 7
beta = 11

alpha,beta = aFunc(alpha,beta)            #function call
In [ ]: