[Tutor] modifying global within function without declaring global

Alan Gauld alan.gauld at btinternet.com
Wed Jan 9 02:07:57 CET 2013


On 05/01/13 01:27, Nathaniel Huston wrote:

> def deal(quantity):
>
>      hand = []
>      for cards in range(0, quantity):
>          hand.append(deck.pop())
>      return hand

 > #we find that the global deck has been modified within the deal()
 > function without including
 >
 > global deck
 >
 > #within the deal() function

Notice deal() modifies the contents of deck but not deck itself - it 
still points to the same list object.

You only need to use global if you are changing the value. Since you are 
only modifying the contents you don't need the global statement.

You have to think in terms of objects and names as references to the 
objects. If you are changing the object that the name refers to you need 
to use global. If you are only changing the content of the object then 
there is no need for global. The object here is the list.

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/



More information about the Tutor mailing list