Reputation: 31
options = [ "Choice 1: 1-9", "Choice 2: 10- 100", ]
button = buttonbox ( msg = "Choose your range of numbers", title = "Select number range", choices = options)
if button == "Choice 1: 1-9":
from random import randint
rn1 = randint(30,50)
from random import randint
rn2 = randint(30,50)
options = [ "Close"]
buttonbox ( msg = "%s X %s = ___" % (rn1, rn2), title = "Select number range", choices = options)
if button == "Choice 2: 10- 100":
from random import randint
rn2 = randint (10,100)
from random import randint
rn2 = randint (10,100)
options = [ "Close"]
buttonbox ( msg = "%s X %s = ___" % (rn1, rn2), title = "Select number range", choices = options)
This is my code, when I try and run the second choice, it says NameError: name 'randint' is not defined
even though the code is exactly the same as the first option, but with different numbers.
Any suggestions?
Upvotes: 2
Views: 40947
Reputation: 6597
Only import randint once, at the top of the file. Put from random import randint
at the top of the program and remove it in all other places. I think this is what you want:
from random import randint
options = ["Choice 1: 1-9", "Choice 2: 10- 100"]
button = buttonbox(msg="Choose your range of numbers", title="Select number range", choices=options)
if button == options[0]:
rn1 = randint(30, 50)
rn2 = randint(30, 50)
elif button == options[1]:
rn1 = randint(10, 100)
rn2 = randint(10, 100)
options = ["Close"]
buttonbox (msg="%s X %s = ___" % (rn1, rn2), title="Select number range", choices=options)
Upvotes: 8
Reputation: 399
I suspect that button is not equal to "Choice 1: 1-9". It might have some trailing whitespaces or a new line charecter. Try printing it to verify that. You can remove those by using strip.
In any case, as EdChum mentioned, it is not recommended to have conditional imports. Even worse, you are importing the same module two lines down. I am not sure if you want do that, but I would suggest to put the rn1 definition in the check instead.
Upvotes: 0