Difference between revisions of "CSC111 Exercises with Functions"

From dftwiki3
Jump to: navigation, search
(Created page with '<tanbox> Figure out the behavior of the program below. Sketch its use of memory (scope) as the Python interpreter executes the program. </tanbox> <br /> ==Exercise 1== <source l…')
 
 
(2 intermediate revisions by the same user not shown)
Line 1: Line 1:
 
<tanbox>
 
<tanbox>
Figure out the behavior of the program below.  Sketch its use of memory (scope) as the Python interpreter executes the program.
+
Figure out the behavior of the programs below.  Sketch their use of memory (scope) as the Python interpreter executes the program.
 
</tanbox>
 
</tanbox>
 
<br />
 
<br />
Line 44: Line 44:
 
     f1( a+b, 3 )
 
     f1( a+b, 3 )
 
     f2( a, 4 )
 
     f2( a, 4 )
 +
 +
main()
 +
 +
</source>
 +
 +
==Exercise 3==
 +
<source lang="python">
 +
def f1( a, b )
 +
    for i in range( b ):
 +
        print a,
 +
    print
 +
 +
def f2( a, b )
 +
    f1( '-', 20 )
 +
    f1( a, 10 )
 +
    f1( b, 5 )
 +
   
 +
def main( ):
 +
    f2( ' ', ' ' )
 +
    f2( 5, 6 )
 +
    f2( "hello", "there" )
  
 
main()
 
main()
  
 
</source>
 
</source>

Latest revision as of 08:02, 24 February 2010

Figure out the behavior of the programs below. Sketch their use of memory (scope) as the Python interpreter executes the program.


Exercise 1

def f1( a ):
    print '-' * 40
    print a
    print '-' * 40

def f2( b ):
    print "parameter = ", b

def main():
    a = 3
    b = 5
    f1( a )
    f2( a )
    f1( b )
    f2( b+a+10 )
 
main()

Exercise 2

def f1( a, b ):
    print a, '-',  b, '=', a - b

def f2( b, c ):
    a = b + c
    print 'a = ', a

def main():
    a = 3
    b = 4
    c = 6
    z = 10
    f1( a, b )
    f1( b, c )
    f1( a+b, 3 )
    f2( a, 4 )

main()

Exercise 3

def f1( a, b )
    for i in range( b ):
        print a,
    print

def f2( a, b )
    f1( '-', 20 )
    f1( a, 10 )
    f1( b, 5 )
    
def main( ):
    f2( ' ', ' ' )
    f2( 5, 6 )
    f2( "hello", "there" )

main()