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
Answers:
Add result = 0
before your for loop.
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.
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?
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.
===================================
| *** 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
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
Add result = 0
before your for loop.
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.
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?
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.