Difference between revisions of "CSC111 Exercises with Global Variables"

From dftwiki3
Jump to: navigation, search
(Case)
Line 162: Line 162:
 
<br />
 
<br />
  
=Case  =
+
=Case  6=
 
<br />
 
<br />
 
{| class="wikitable" style="width:100%;"
 
{| class="wikitable" style="width:100%;"
Line 168: Line 168:
 
<br />
 
<br />
 
<source lang="python">
 
<source lang="python">
+
 
 +
def f1( x ):
 +
    global A
 +
    A = []   
 +
    print( "f1", x, A )
 +
    A.append( 10 )
 +
    A.append( 20 )
 +
    print( "f1", x, A )
 +
 
 +
A = [1, 2, 3]
 +
print( "A = ", A )
 +
f1( 30 )
 +
print( "A = ", A )
 +
 
  
 
</source>
 
</source>
Line 175: Line 188:
 
<source lang="text">
 
<source lang="text">
 
>>>  
 
>>>  
 
+
A =  [1, 2, 3]
 +
f1 30 []
 +
f1 30 [10, 20]
 +
A =  [10, 20]
  
 
>>>  
 
>>>  
Line 183: Line 199:
 
<!-- ---------------------------------------------------------------------------------------------- -->
 
<!-- ---------------------------------------------------------------------------------------------- -->
 
<br />
 
<br />
 +
 
=Case  =
 
=Case  =
 
<br />
 
<br />

Revision as of 18:28, 24 April 2014

--D. Thiebaut (talk) 15:57, 24 April 2014 (EDT)



Explain the behavior of the different code sections shown below along with their output.

Case 1



A = 3

def f1( x ):
    print( "f1", x, A )

print( "A = ", A )
f1( 30 )


>>> 
A =  3
f1 30 3
>>>




Case 2



def f1( x ):
    print( "f1", x, A )

A = 3
print( "A = ", A )
f1( 30 )


>>> 
A =  3
f1 30 3
>>>


Case 3



A = 3

def f1( x ):
    print( "f1", x, A )
    A = 5
    
print( "A = ", A )
f1( 30 )
print( "A = ", A )


>>> 
A =  3
Traceback (most recent call last):
 File "/Users/thiebaut/Desktop/PYTHON/globalExercises.py", line 8, in <module>
   f1( 30 )
 File "/Users/thiebaut/Desktop/PYTHON/globalExercises.py", line 4, in f1
   print( "f1", x, A )
UnboundLocalError: local variable 'A' referenced before assignment

>>> 


Case 4



A = 3

def f1( x ):
    global A
    print( "f1", x, A )
    A = 5
    
print( "A = ", A )
f1( 30 )
print( "A = ", A )


>>> 
A =  3
f1 30 3
A =  5
>>>


Case 5



def f1( x ):
    A = []    
    print( "f1", x, A )
    A.append( 10 )
    A.append( 20 )
    print( "f1", x, A )

A = [1, 2, 3]
print( "A = ", A )
f1( 30 )
print( "A = ", A )


>>> 
A =  [1, 2, 3]
f1 30 []
f1 30 [10, 20]
A =  [1, 2, 3]
>>>


Case 6



def f1( x ):
    global A
    A = []    
    print( "f1", x, A )
    A.append( 10 )
    A.append( 20 )
    print( "f1", x, A )

A = [1, 2, 3]
print( "A = ", A )
f1( 30 )
print( "A = ", A )


>>> 
A =  [1, 2, 3]
f1 30 []
f1 30 [10, 20]
A =  [10, 20]

>>>


Case





>>> 


>>>