liv2hak
liv2hak

Reputation: 14990

NameError: name 'result' is not defined

I have written a very simple program in python

 for i in range(1,1000):
     if (i % 3 == 0) and (i % 5 == 0) :
           result += i

 else:
      print('sum is {}'.format(result))

When I try to compile the problem I am getting the error.

NameError: name 'result' is not defined

Upvotes: 1

Views: 19178

Answers (4)

Wyrmwood
Wyrmwood

Reputation: 3599

or...

try: 
    result += i
except:
    result = i

but this won't get you past what happens if the loop condition never occurs (you would need another try in your printout), so just setting it prior to the loop is probably better.

Upvotes: 0

Schechter
Schechter

Reputation: 223

First of all, your indentation is inconsistent and incorrect which makes it harder to read.

result = 0
for i in range(1,1000):
    if (i % 3 == 0) and (i % 5 == 0) :
        result += i
    else:
        print 'sum is ',result

This is the way to get around your error, but I don't think this is actually what you're trying to do. What is the problem you're trying to solve?

Upvotes: 1

Santa
Santa

Reputation: 11545

This statement:

result += i

is equivalent to:

result = result + i

But, the first time this statement is reached in your loop, the variable result has not been defined, so the right-hand-side of that assignment statement does not evaluate.

Upvotes: 3

AliBZ
AliBZ

Reputation: 4099

Add result = 0 before your for loop.

Upvotes: 2

Related Questions