Chapter 4: Variable Scope and Modular Programming

C16FUN1, Page number:338

In [1]:
#Function Definition
def next_fun():                         
    print "Inside next_fun()"    
def third_fun():                        
    print "Inside third_fun()"
def main():                             
    print "First function called main()"
    #Function Call
    next_fun()                          
    third_fun()                     
    print "main() is completed"
#Function Call
main() 
First function called main()
Inside next_fun()
Inside third_fun()
main() is completed

C16FUN2, Page number:347

In [2]:
#Function Calls
def name_print():
    print "C++ is Fun!\tC++ is Fun!\tC++ is Fun!"
    print " C++ i s F u n ! \t C++ i s F u n ! \t C++ i s F u n ! "
    reverse_print()                         
def reverse_print():
    print "!nuF si ++C\t!nuF si ++C\t!nuF si ++C"
def one_per_line():
    print "C++\n i\n s\n F\n u\n n\n !"
def main():
    for ctr in range(1,6,1):
        name_print()                            #Calls function five times.
    one_per_line()                             #Calls the program's last function once 
main()
C++ is Fun!	C++ is Fun!	C++ is Fun!
 C++ i s F u n ! 	 C++ i s F u n ! 	 C++ i s F u n ! 
!nuF si ++C	!nuF si ++C	!nuF si ++C
C++ is Fun!	C++ is Fun!	C++ is Fun!
 C++ i s F u n ! 	 C++ i s F u n ! 	 C++ i s F u n ! 
!nuF si ++C	!nuF si ++C	!nuF si ++C
C++ is Fun!	C++ is Fun!	C++ is Fun!
 C++ i s F u n ! 	 C++ i s F u n ! 	 C++ i s F u n ! 
!nuF si ++C	!nuF si ++C	!nuF si ++C
C++ is Fun!	C++ is Fun!	C++ is Fun!
 C++ i s F u n ! 	 C++ i s F u n ! 	 C++ i s F u n ! 
!nuF si ++C	!nuF si ++C	!nuF si ++C
C++ is Fun!	C++ is Fun!	C++ is Fun!
 C++ i s F u n ! 	 C++ i s F u n ! 	 C++ i s F u n ! 
!nuF si ++C	!nuF si ++C	!nuF si ++C
C++
 i
 s
 F
 u
 n
 !

C17GLO, Page number:356

In [4]:
def do_fun():
    global sales                      #global variable
    global profit                    #global variable 
    sales = 20000.00
    profit=5000.00
    print "The sales in the second function are: ",sales
    print "The profit in the second function is: ",profit
    third_fun()                     #Call third function to show that globals are visible
def third_fun():
    print "\nIn the third function:"
    print "The sales in the third function are",sales
    print "The profit in the third function is ",profit
def main():
    print "No variable defined in main()\n"
    do_fun()
main()
No variable defined in main()

The sales in the second function are:  20000.0
The profit in the second function is:  5000.0

In the third function:
The sales in the third function are 20000.0
The profit in the third function is  5000.0

C17GLLO, page number:358

In [5]:
def pr_again():
    j=5                             #Local to only pr_again().
    print j,",",z,",",i
global i
i=0
def main():
    p=9.0                        #Local to main() only
    print i,",",p
    pr_again()                  #Calls next function.

global z
z=9.0
main()          
0 , 9.0
5 , 9.0 , 0

C17LOC1, Page number:359

In [6]:
def main():
    age=input("What is your age? ")              #Variable age is local to main()
    get_age()
    print "main()'s age is still",age    
def get_age():
    age=input("What is your age again? ") #A different age. This one is local to get_age().
main()                          
What is your age? 28
What is your age again? 56
main()'s age is still 28

C17LOC2, Page number:360

In [7]:
def main():
    for ctr in range(0,11,1):               #Loop counter
        print "main()'s ctr is ",ctr,"\n"
    do_fun()                                #Call second function

def do_fun():
    for ctr in range(10,0,-1):
        print "do_fun()'s ctr is ",ctr,"\n"
main()
main()'s ctr is  0 

main()'s ctr is  1 

main()'s ctr is  2 

main()'s ctr is  3 

main()'s ctr is  4 

main()'s ctr is  5 

main()'s ctr is  6 

main()'s ctr is  7 

main()'s ctr is  8 

main()'s ctr is  9 

main()'s ctr is  10 

do_fun()'s ctr is  10 

do_fun()'s ctr is  9 

do_fun()'s ctr is  8 

do_fun()'s ctr is  7 

do_fun()'s ctr is  6 

do_fun()'s ctr is  5 

do_fun()'s ctr is  4 

do_fun()'s ctr is  3 

do_fun()'s ctr is  2 

do_fun()'s ctr is  1 

C17MULI, Page number:362

In [1]:
def main():
    i=10
    i=20
    print i," ",i,"\n"
    i=30
    print i," ",i," ",i,"\n"    
    i=10
    print i," ",i," ",i 
main()
20   20 

30   30   30 

10   10   10

C17LOC3, Page number:367

In [3]:
def pr_init(initial):
    print "Your initial is ",initial
def pr_other(age,salary):
    print "You look young for",age,"and ",'%.2f' %salary,"is a lot of money"
initial=raw_input("What is your initial?")
age=input("What is your age?")
salary=input("What is your salary?")
pr_init(initial)                        #call pr_init() and pass it initial
pr_other(age,salary)                #call pr_other and pass age and salary
What is your initial?Jerry
What is your age?30
What is your salary?50000
Your initial is  Jerry
You look young for 30 and  50000.00 is a lot of money

C17LOC4, Page number:368

In [4]:
def compute_sale(gallons):
    #local variable
    price_per=12.45                         
    x=price_per*float(gallons)          #type casting gallons because it was integer
    print "The total is ",'%.2f' %x
def main():
    print "Richard's Paint Service"
    gallons=input("How many gallons of paint did you buy?")
    compute_sale(gallons)                   #Function Call
main()
Richard's Paint Service
How many gallons of paint did you buy?20
The total is  249.00

C17STA2, Page number:372

In [5]:
def main():
    for ctr in range(1,26,1):
        triple_it(ctr)
def triple_it(ctr):
    total=0
    ans=ctr*3
    total+=ans
    print "The number ",ctr,"multiplied by 3 is ",ans
    if total>300:
        print "The total of triple numbers is over 300"
main()
The number  1 multiplied by 3 is  3
The number  2 multiplied by 3 is  6
The number  3 multiplied by 3 is  9
The number  4 multiplied by 3 is  12
The number  5 multiplied by 3 is  15
The number  6 multiplied by 3 is  18
The number  7 multiplied by 3 is  21
The number  8 multiplied by 3 is  24
The number  9 multiplied by 3 is  27
The number  10 multiplied by 3 is  30
The number  11 multiplied by 3 is  33
The number  12 multiplied by 3 is  36
The number  13 multiplied by 3 is  39
The number  14 multiplied by 3 is  42
The number  15 multiplied by 3 is  45
The number  16 multiplied by 3 is  48
The number  17 multiplied by 3 is  51
The number  18 multiplied by 3 is  54
The number  19 multiplied by 3 is  57
The number  20 multiplied by 3 is  60
The number  21 multiplied by 3 is  63
The number  22 multiplied by 3 is  66
The number  23 multiplied by 3 is  69
The number  24 multiplied by 3 is  72
The number  25 multiplied by 3 is  75

C18PASS1, Page number:381

In [6]:
def moon(weight):           
    weight/=6               
    print "You weigh only ",weight,"pounds on the moon !"
def main():                     
    weight=input("How many pounds do you weigh?  ")
    moon(weight)                #call the moon() function and pass weight
main()
How many pounds do you weigh?  120
You weigh only  20 pounds on the moon !

C18PASS3, Page number:383

In [7]:
def main():
    Igrade=raw_input("What letter grade do you want?")
    average=input("What is your current test average")
    tests=input("How many tests do you have left?")
    check_grade(Igrade,average,tests)           #// Calls function and passes three variables by value
def check_grade(Igrade,average,tests):
    if tests==0:
        print "You will get your current grade of ",Igrade
    else:
        if tests==1:
            print "You still have time to bring up your average of",'%.1f' %average,"up . Study hard !"
        else :
            print "Relax. You still have plenty of time."    
main()
What letter grade do you want?A
What is your current test average1
How many tests do you have left?3
Relax. You still have plenty of time.

C19AVG, Page number:398

In [10]:
def calc_av(num1,num2,num3):
    local_avg=(num1+num2+num3) / 3          #Holds the average for these numbers
    return local_avg
print "please type three numbers (such as 23 54 85) "
num1=input()
num2=input()
num3=input()
avg=calc_av(num1,num2,num3)             #call function and pass the numbers
print "\n\nThe average is ",avg             #Print the return value
please type three numbers (such as 23 54 85) 
30
40
50


The average is  40

C19DOUB, Page number:401

In [11]:
def doub(number):
    d_num=number*2                              #Doubles the number.
    return d_num                                #Returns the result.
number=input("What number do you want doubled? ")
d_number= doub(number)                       #Assigns return value.
print number," doubled is ",d_number
What number do you want doubled? 5
5  doubled is  10

C19SUMD, Page number:403

In [13]:
def sums(num):
    sumd=0
    if num<=0:
        sumd=num
    else:
        for ctr in range(1,num+1,1):
            sumd=sumd+ctr
    return sumd
num=input("Please type a number: ")
sumd= sums(num)
print "The sum of the digits is " , sumd
Please type a number: 6
The sum of the digits is  21

C19MINMX, Page number:404

In [14]:
def maximum(num1,num2):             
    if  num1>num2:
        maxi=num1
    else:
        maxi=num2
    return maxi
def minimum(num1,num2):
    if  num1>num2:
        mini=num2
    else:
        mini=num1
    return mini
print "Please type two numbers ( such as 46 75 ) "
num1 = input()
num2 = input()
maxi=maximum(num1,num2)         #Assign the return value of each function to variables
mini=minimum(num1,num2)         
print "The minimum number is ",mini
print "The maximum number is ", maxi
Please type two numbers ( such as 46 75 ) 
72
55
The minimum number is  55
The maximum number is  72

C19PRO1, Page number:409

In [15]:
tax_rate=0.07           #Assume seven percent tax rate
total_sale=input("What is the sale amount? ")
total_sale+=tax_rate*total_sale
print "The total sale is ",'%.2f' %total_sale
What is the sale amount? 4000
The total sale is  4280.00

C19ASC, Page number:410

In [16]:
def ascii(num):
    asc_char=chr(num)           #Type cast to a character
    return asc_char
num=input("Enter an ASCII number? ")
asc_char=ascii(num)             #Number is passed to the function ascii()
print "The ASCII character for ",num,"is ",asc_char
Enter an ASCII number? 67
The ASCII character for  67 is  C

C19NPAY, Page number:411

In [17]:
def netpayfun(hours,rate,taxrate):
    gross_pay=hours*rate
    taxes=taxrate*gross_pay
    net_pay=gross_pay-taxes
    return net_pay
net_pay=netpayfun(40.0,3.50,0.20)
print "The pay for 40 hours at $3.50/hr., and a 20% tax rate is $ ",net_pay
net_pay=netpayfun(50.0,10.00,0.30)
print "The pay for 40 hours at $10.00/hr., and a 30% tax rate is $ ",net_pay
net_pay=netpayfun(10.0,5.00,0.10)
print "The pay for 40 hours at $5.00/hr., and a 10% tax rate is $ ",net_pay
The pay for 40 hours at $3.50/hr., and a 20% tax rate is $  112.0
The pay for 40 hours at $10.00/hr., and a 30% tax rate is $  350.0
The pay for 40 hours at $5.00/hr., and a 10% tax rate is $  45.0

C20OVF1, Page number:423

In [18]:
i=-15
x=-64.53
ians=abs(i)             #abs() function is a built in function that returns a positive value 
print "Integer absolute value of -15 is ",ians
fans=abs(x)
print "Float absolute value of -64.53 is ",'%.2f' %fans
Integer absolute value of -15 is  15
Float absolute value of -64.53 is  64.53

C20OVF2, Page number:424

In [19]:
#function definition
def output(x):
    if isinstance(x,int):
        print x
    else:
        if isinstance(x,float):
            print '%.2f' %x
        else:
            print x
#Variable Decleration
name="C++ By Example makes C++ easy!"
Ivalue=2543
fvalue=39.4321
#calling function
output(name)
output(Ivalue)
output(fvalue)
C++ By Example makes C++ easy!
2543
39.43