So after pretty much giving up on programming (I think I should say that I kinda forgot about it actually) and not checking Daniweb, I decided after a few months of doing other things I'd come back to Daniweb and start trying to program once again.

After skimming through "Learn Python the Hard Way" to refresh my memory, I decided I'd practice a bit and now I'm having a bit of a problem; and because I can't seem to figure it out my brain's in a state of total frustration and meltdown.

Why does this give me a NameError?

def something():
    a = raw_input('>> ')
    return a

something()
print a

Recommended Answers

All 4 Replies

You are not saving the value returned from something to global variable, so global variable a is uninitialized. print(something()) would work or adding 'a = ' in beginning of line 5.

It is good to start to practice correct naming from beginning, even I understand you are doing proof of concept. My version (interactive testing in IDLE command prompt):

>>> def input_default(prompt='>> '):
	return raw_input(prompt)
>>> print(input_default())
>> Python is neat language!
Python is neat language!
>>>

Tony has explain this,just a little more with code.

def something():
    a = raw_input('>> ')
    return a

print something()

As you something() has the return value.

def something():
    a = raw_input('>> ')
    return a

a = something() #store it in variable a
print a

One important fact with functions is that code local to that function,you have to call it.
That why a is not leaked out in global space.

No it work with making a global,but this is ugly and dont code like this.

def something():
    global a
    a = raw_input('>> ')
    return a

something()
print a

Forgetting to assign the function call's return to a variable is a common mistake for beginners. As Snippsat pointed out, the variable 'a' within the function is local and stays there. Keep plugging along.

Just to reiterate, your code should have been ...

def something():
    a = raw_input('>> ')
    return a

a = something()
print a
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.