[Tutor] Variables and Functions
Devon MacIntyre
macintyredev at gmail.com
Thu Nov 29 02:51:39 CET 2007
Hi,
I have two functions, 'new_sudoku' and 'play_game'. In new_sudoku, I have a
pre-determined puzzle (I wasn't able to get a randomly generated puzzle
working), as a matrix in the variable 'puzzle'. I imported the 'copy' module
and made a deep-copy of 'puzzle' to make 'new_puzzle', which randomly has
85% of the digits replaced by an empty string. Now that 'new_puzzle' is only
15% filled with numbers, I use turtle to place the numbers on a grid that I
made (also with turtle). After the grid and 'new_puzzle' are generated, I
ask the player if he/she wants to begin playing. If yes, then the function
'play_game' is started. Here, I'm going to let the player choose spots to
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:
def swap_row(puzzle,row1,row2):
temp = puzzle[row1]
puzzle[row1] = puzzle[row2]
puzzle[row2] = temp
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] = ''
def play_game():
'''
Here is where I need the variables 'puzzle' and 'new_puzzle' to be
brought.
'''
I read about the 'class' module, but am not sure on it's execution. I really
appreciate any time spent on my (simple) problem.
Thanks in advance.
On Nov 28, 2007 4:18 PM, Kent Johnson <kent37 at tds.net> wrote:
> Devon MacIntyre wrote:
> > Hi,
> > Just wondering, how would I get a variable out of one function and into
> > another?
>
> I don't understand your description of your situation, maybe you could
> show a little code as a simple example?
>
> The usual way to get a variable out of a function is to return a value
> from the function. The usual way to get a variable into a function is to
> pass a parameter. If you want tighter coupling than that maybe you
> should make the functions into methods of a class and make the variables
> into instance attributes.
>
> HTH,
> Kent
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20071128/f9061173/attachment.htm
More information about the Tutor
mailing list