NameError: name 'result' is not defined - python

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

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.

Add result = 0 before your for loop.

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.

Related

My code is working but with no outputs, what is the problem?

What is the problem?
i even tried this at the starting soas to get a output
print("enter list elements")
arr = input()
def AlternateRearr(arr, n):
arr.sort()
v1 = list()
v2 = list()
for i in range(n):
if (arr[i] % 2 == 0):
v1.append(arr[i])
else:
v2.append(arr[i])
index = 0
i = 0
j = 0
Flag = False
#set value to true is first element is even
if (arr[0] % 2 == 0):
Flag = True
#rearranging
while(index < n):
#if 1st elemnt is eevn
if (Flag == True):
arr[index] = v1[i]
index += 1
i+=1
Flag = ~Flag
else:
arr[index] = v2[j]
index +=1
j += 1
Flag = ~Flag
for i in range(n):
print(arr[i], end = "" )
arr = [9, 8, 13, 2, 19, 14]
n = len(arr)
AlternateRearr(arr, n)
print(AlternateRearr(arr))
There's no error.
Just the driver code dosen't work i guess, there's no output.
no outputs
The only place where it could output anything is print(AlternateRearr(arr)). But let's take a look at AlternateRearr itself - what does it return?
There's no return statement anywhere in AlternateRearr, so the print would show None. Well, it's something, not completely nothing...
But the code doesn't reach this part anyway - if it did, it would throw an error because print(AlternateRearr(arr)) passes only one argument to the function AlternateRearr that takes 2 arguments. You don't have default value set for n, so it wouldn't work.
Okay, so we came to conclusion that we don't reach the print anyway. But why? Because you never call it. You only define it and it's a different thing from calling it.
You might encounter a problem if you just try calling it near your normal code - Python is an interpreted language, so your main-level code (not enclosed in functions) should be at the bottom of the file because it doesn't know anything that is below it.
Is that your complete code?
Because you do have a function called AlternateRearr but you never call it
Call the function and also pass the integer for iteration.
Add after the function:
AlternateRearr(arr, 5)

Name 'absolute value' not defined in Python

So I am really knew to coding, this is problem occurred about 5 minutes after I started. So I am currently doing this Coursera course made by an associate professor at Wesleyan (https://www.coursera.org/learn/python-programming-introduction). One of the exercises was:
Write a function absolutevalue(num) that computes the absolute value of
a number. You will need to use an 'if' statement. Remember if a number is less than zero then you must multiply by -1 to make it greater than zero.
So I figured my answer should be something like this:
absolutevalue(num):
""" Computes the absolute value of a number."""
if num >> 0:
absolutevalue =num
print(absolute value)
elif num<< 0:
absolutevalue == -1*num
print(absolutevalue)
else:
print("Absolute value is 0")
But when I run the code the console keeps saying:
Traceback (most recent call last):
File "", line 1, in
absolutevalue(5)
NameError: name 'absolutevalue' is not defined
For the past hour, I have been trying to fix the problem, yet I don't know how.
Could someone please help me, and keep in mind this is one of my first times trying to code something.
Thanks
A few errors:
Your def statement is missing. Normally a function definition should start with a line like def absolutevalue(num) rather than just absolutevalue(num).
You're using double comparators >> where you should be using single ones >. The former is a bit-shifting operator.
Within the function, you're using a variable with the same name as the function itself: absolutevalue. It's not necessarily wrong, but definitely not particularly handy.
Your function doesn't actually return the absolute value; it just prints it.
Edit: now that your question has been edited to use code blocks: your indentation is missing. :)
Hope that helps!
Function definitions in python need to start with def. Function blocks also need to be indented correctly, for example:
def absolutevalue(num):
""" Computes the absolute value of a number."""
if num > 0:
return num
elif num < 0:
return -1 * num
return 0
print(absolutenumber(-1))
print(absolutenumber(1))
print(absolutenumber(0))
>>> 1
>>> 1
>>> 0
You need to define the function absolutevalue and pass num into it. If you need to return the value instead, use return rather than print()
def absolutevalue(num):
if num > 0:
print(num)
elif num < 0:
abs_value = num * -1
print(abs_value)
else:
print("Absolute value is 0")

Return and assignment in recursive function in python: None type given, expected an int value

I am fairly new to python but worked with recursion previously. I came across this problem while working with recursive functions.
archive = {1: 0}
def engine(base, chain=0):
if base in archive:
return archive[base]
else:
if base == 1:
return chain
elif base % 2 == 0:
get = engine(base/2)
meaning = 1 + get
archive[base] = meaning
else:
next = 3 * base + 1
get = engine(next)
meaning = 1 + get
archive[base] = meaning
print archive(13)
I worked with scheme recently. So, I expected it to work.
I want the code to evaluate till the case bool(base==1) becomes true and then work it's way up ward making a new entry to the dictionary on each level of recursion.
How can I achieve that? I am just counting the level of recursion until the fore-mentioned condition becomes True with the variable 'chain'.
[Solved]: I missed the return statement in two clauses of if-else statement. The scheme would pass the function itself and the last return statement would do the work but not with python. I understand it now.
Thanks everyone who responded. It was helpful.
Your last two elif and else clauses have no return statements and Python returns None by default.

What causes my function to return None at the end? [duplicate]

This question already has answers here:
Why is "None" printed after my function's output?
(7 answers)
Closed 7 months ago.
My very simple python function is returning None at the end of it and I'm not sure quite why. I've looked at some other posts and still can't figure it out.
Here is my code:
def printmult(n):
i = 1
while i <= 10:
print (n * i, end = ' ')
i += 1
print(printmult(30))
Because in Python, every function returns a value, and None is what is returned if you don't explicitly specify something else.
What exactly did you expect print(printmult(30)) to do? You've asked it to evaluate printmult(30), and then print whatever results from that. Something has to result from it, right? Or were you maybe expecting some kind of exception to be raised?
Please be sure you understand that printing and returning are not the same thing.
You are not returning anything in the function printmult, therefore when you print the result of printmult(30) it will be None (this is the default value returned when a function doesn't return anything explictly).
Since your method have a print statement inside and it's not supposed to return something (usually when a method names is something like printSomething(), it doesn't return anything), you should call it as:
printmult(30)
not
print(printmult(30))
The other answers have done a good job of pointing out where the error is, i.e. you need to understand that printing and returning are not the same. If you want your function to return a value that you can then print or store in a variable, you want something like this:
def returnmult(n):
i = 1
result_string = ''
while i <= 10:
result_string += str(n * i) + ' '
i += 1
return result_string
print(returnmult(30))
def printmult(n):
i = 1
while i <= 10:
print (n * i, end = ' ')
i += 1
printmult(30)
The issue was that you were printing the return value of a function that returns nothing, which would print None
I came from Ruby as well and it seems strange at first.
If you print something that has a print statement in it, the last thing it returns is None.
If you just returned the values and then invoked a print on the function it would not output None.
Hope this helps :)

syntax error on line: `if x.isupper() and not in y`

I'm getting "invalid syntax" errors pointing to the "in" statement. What's my mistake?
while(notes > 1):
note = choice(scale)
if note[0].isupper() and not in patternNotes:
patternNotes.append(note)
notes -= 1
elif note is not rootNote and note not in patternNotes:
patternNotes.append(note)
notes -= 1
You probably want
if note[0].isupper() and note not in patternNotes:
rather than
if note[0].isupper() and not in patternNotes:
Note the lacking note in the second one.
It should be note[0].isupper() and note not in patternNotes: (notice the second note before not)
After that your syntax is fine:
i = {}
j = {}
print i is not j and j not in {}
# False
Note that this is an infinite loop under certain conditions, like "note in patternNotes". Move the "notes -= 1" statement outside the if/elif and the problem is solved.

Categories