[Tutor] Variables and Functions

Ricardo Aráoz ricaraoz at gmail.com
Fri Nov 30 14:04:36 CET 2007


Alan Gauld wrote:
> "Devon MacIntyre" <macintyredev at gmail.com> wrote
> 
>> input their own numbers to fill in the board. My problem is that I 
>> can't get
>> the variables 'puzzle' and 'new_puzzle' into that function (to be 
>> compared)
>> because they are not globally defined; only in 'new_sudoku' 
>> function. Here's
>> some selected code from my program:
> 
> As per my prevuiouis email and example, simply return the puzzles
> 
>> def swap_row(puzzle,row1,row2):
>>    temp = puzzle[row1]
>>    puzzle[row1] = puzzle[row2]
>>    puzzle[row2] = temp
>       return puzzle   # just to be safe and consistent
> 
>> def new_sudoku():
>>    puzzle = [[1,2,3,4,5,6,7,8,9], \
>>              [4,5,6,7,8,9,1,2,3], \
>>              [7,8,9,1,2,3,4,5,6], \
>>              [2,3,4,5,6,7,8,9,1], \
>>              [5,6,7,8,9,1,2,3,4], \
>>              [8,9,1,2,3,4,5,6,7], \
>>              [3,4,5,6,7,8,9,1,2], \
>>              [6,7,8,9,1,2,3,4,5], \
>>              [9,1,2,3,4,5,6,7,8]]
>>    num_of_swap = random.randint(10,20)
>>    for i in range(num_of_swap):
>>        row1 = random.randint(0,8)
>>        row2 = random.randint(0,8)
>>        if row1/3 == row2/3:
>>            swap_row(puzzle,row1,row2)
>>    new_puzzle = copy.deepcopy(puzzle)
>>    sparseness = 0.85
>>    for i in range(9):
>>        for j in range(9):
>>            if random.uniform(0,1) < sparseness:
>>                new_puzzle[i][j] = ''
>       return puzzle,new_puzzle
> 
>> def play_game():
>>    '''
>>    Here is where I need the variables 'puzzle' and 'new_puzzle' to 
>> be
>> brought.
>>    '''
> 
> original,new = new_sudoku()
> compare(original,new)
> 
> 
>> I read about the 'class' module, but am not sure on it's execution.
> 
> I'm not sure what the class module is? Its not one of the standard
> Python modules. If you mean the class construct that is not a module
> but a part of the language - like def is for functions.
> 
> See the OOP topic of my tutor for more info on how to use it.
> 
> But for this problem you don;t need classes, just pass the data
> out of one function and into the other as shown above.
> Have a read of the Modules & Functions topic in my tutor for
> more explanation.
> 

Right! This is not something that needs OOP!
Besides, I find this belief that inside a class everything goes
completely wrong. In that case you could write your code with globals
and do whatever, then wrap it in a class, make your globals to be
properties and voilá,  every thing's all right. I don't think that is
the way to go.





More information about the Tutor mailing list