The variable “difference” isn’t defined

num=int(input("Please enter a number: "))
square=numnum
cube=square
num
def diff():
difference=cube-square
return(difference)
print(square)
print(cube)
diff()
print(difference)

this is my code and it is saying that the variable “difference” isn’t defined.

Where is the variable defined?

i tried to define it in the procedure and then again outside the procedure but both times produced a syntax error

By procedure, do you mean, ‘function’? Perhaps move the function definition to the top, and write everything that is not in the function below that. Then post your formatted code in a new reply.

If you’ve not read the Getting Started section of the forums, take a minute now to go over it. Included are instructions on how to post code samples using markdown.

num=int(input("Please enter a number: "))
square=num*num
cube=square*num
def diff():
    difference=cube-square
    return difference
diff()
print(square)
print(cube)
print(difference)

it is still producing the same result

1 Like

What is that line actually doing?

I was trying to run the function

Where is the result?

print(difference)

NameError: name ‘difference’ is not defined

Are you forgetting something?

I’m not sure if i am

What should we be doing with the return value?

creating it into a global variable?

As in, assign it?

yes, that is what i meant

So where is that assignment?

I haven’t included that as i forgot to do so

Go ahead and try, now. Give it a different name than the one used inside the function so the two stand out. Please post your revised code in a reply so we can go over it, for posterity.

num=int(input("Please enter a number: "))
square=num*num
cube=square*num
def differencebetween():
    difference=cube-square
    return difference
difference=differencebetween()
print(square)
print(cube)
print(difference)

Let’s make it a practice to define functions at the top of our code:

def difference_between():
    '''a function to find the difference between two numbers'''
    diff = cube - square
    return diff

Functions are the primary objects of our program. If they are all at the top, we can get a better inventory of them. For illustration we’ve included the doc_string as our first line. This facilitates Python’s built in, help() function.

>>> help(difference_between)
a function to find the difference between two numbers
>>>

Next we can initialize our running variables.

num = int(input("Please enter a number: "))

print (num)      # remove after debugging

square = num * num
cube = square * num

print (square)    # remove after debugging
print (cube)      # remove after debugging

difference = difference_between()  # note different name

print (difference)

We can dress up the final outcome if we want to be thorough:

print (f"The difference between {cube} and {square} is {difference}")

All of this will become second nature with study and practice (lots of it).