Reputation: 21
I am trying to make a program that calculates the biggest number of objects(nuggets) you can't get with packages of 6-9-20 (I am fairly new to python, i trying using global and nonlocal but it doesn't work either).
def nuggets(n):
x = 6
y = 9
z = 20
for i in range(0,n//x+1):
for j in range(0,n//y+1):
for k in range(0,n//z+1):
if i*x + j*y + k*z == n:
return [i,j,k]
return None
def cant_buy(n):
seq=0
for i in range(n):
p=nuggets(i)
if type(p)== list:
seq+=1
elif type(p)== None:
cb=i
seq=0
return cb
Then this error appears: Traceback (most recent call last): File "", line 1, in cant_buy(12) File "C:\Python33\OCW 6.00\ps2a.py", line 22, in cant_buy return cb NameError: global name 'cb' is not defined
What is wrong? I defined it at the elif statement.
Upvotes: 2
Views: 1234
Reputation: 11
When I run your code, I got a slightly different yet maybe more clarifying error message. It said: "UnboundLocalError: local variable 'cb' referenced before assignment"
So Python tried to use a variable that was unkown yet.
To declare your variable "cb" before you use it in your loop like so:
def cant_buy(n):
cb = 0 # <---- insert this
seq=0
for i in range(n):
p=nuggets(i)
if type(p)== list:
seq+=1
elif type(p)== None:
cb=i
seq=0
return cb
should do the trick.
Upvotes: 1