-1

So I'm making a lottery number drawing machine,

import random

def lottoDraw1():
    draw1 = random.randint(1,49)

def lottoDraw2():
    draw2 = random.randint(1,49)
    if draw2 == draw1:
        lottoDraw2()

And I get the error, "NameError: name 'draw1' is not defined"

If I insert:

draw1 = 0

before the code, the answer is always 0. Even after I define for draw1 to be changed.

What am I doing wrong?

Jens
  • 20,533
  • 11
  • 60
  • 86
pEW pEW
  • 11
  • 1

2 Answers2

2

What are Python namespaces all about This question is asking for namespaces and that is basicially the problem you are having. In lottodraw1 you are only changing the local version of draw1 and thus the global value of draw1 stays unchanged (in your case 0). For that reason you will always use draw1 = None everywhere else.

My approach would be making an array of the draws and having a general draw function:

draws = []

def draw():
    new_draw = random.randint(1,49)
    if new_draw not in draws:
        draws.append(new_draw)
    else:
        draw()

draw()
draw()
print(draws)

Now you can just call draw and it will add a newly drawn number that does not exist yet.

As noted by Jean-François Fabre the better version would be using sets, which are faster, but only allow unique values:

draws = set()

def draw():
    new_draw = random.randint(1,49)
    if new_draw not in draws:
        draws.add(new_draw)
    else:
        draw()

draw()
draw()
print(draws)
Community
  • 1
  • 1
C.Fe.
  • 325
  • 3
  • 11
  • 1
    With this approach, `draw()` will not draw anything if `new_draw` is in `draws` already. You could just try a new random number as the OP's code does, but it would likely be more efficient to have some way of keeping track of which numbers have been drawn already. – Jack Taylor May 02 '17 at 14:58
  • @Jean-FrançoisFabre Thanks for pointing it out, I made an edit to account for your suggestions – C.Fe. May 02 '17 at 15:05
  • @JackTaylor Your right! Totally forgot to add the recursive call. edited! – C.Fe. May 02 '17 at 15:05
  • good. nitpicking: Just do `draws = set()` (no need to pass an empty list) – Jean-François Fabre May 02 '17 at 15:08
  • @Jean-FrançoisFabre every milisecond and character counts! – C.Fe. May 02 '17 at 15:12
  • :) it's just that when you're answering on SO people have a tendency to take your answer for granted so it better be as good as possible (if not too hassle!) – Jean-François Fabre May 02 '17 at 15:19
0

You need to make draw1 as global variable

draw1, draw2 = None, None

def lottoDraw1():
    global draw1
    draw1 = random.randint(1,49)

def lottoDraw2():
    global draw1
    global draw2
    draw2 = random.randint(1,49)
    if draw2 == draw1:
        lottoDraw2()

However, it is not a good approach which is another topic.

Zohaib Ijaz
  • 21,926
  • 7
  • 38
  • 60