# [Tutor] Variables and Functions

Alan Gauld alan.gauld at btinternet.com
Thu Nov 29 09:43:16 CET 2007

```"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.

--
Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld

```