NameError: name 'result' is not defined

Question:

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
Asked By: liv2hak

||

Answers:

Add result = 0 before your for loop.

Answered By: AliBZ

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.

Answered By: Santa

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?

Answered By: Schechter

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.

Answered By: Wyrmwood

===================================
| *** Area Calculator Program *** |

| Shape code list: |
| (R) Rectangle |
| (T) Trapezoid |
| (P) Parallelogram |

Select Code [R,T,P]: T
You selected T = Trapezoid

Area of Trapezoid

Enter parallel side(a): 8
Enter parallel side(b): 9
Enter height : 2

Area of Trapezoid = 17.00

Answered By: MOS SUPACHAI TAVALA
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.