Didnt i just set the value


#1

I have a question really bothers me:
I try to set some value to some variables in one function:
def function():
parameter1=raw_input(“enter a word for parameter1”)
parameter2=raw_input(“enter a word for parameter2”)

then I set another function which I try to use parameter1 and parameter2 as the parameter input
def function2(parameter1,parameter2):
print parameter1
print parameter2

then I run these two functions:
function()
function(parameter1,parameter2)

it return an error which says parameter1\parameter2 was not defined ,but didnt i just set the value in function()?


FAQ: Learn Python: Functions - Function Junction
#2

Values that are set inside a function are local only, and not accessible to the caller. That is why we have return.

>>> from random import randint
>>> def move(direction):
    spaces = randint(1, 10)
    return "Move %s, %i spaces." % (direction, spaces)

>>> print (move('right'))
Move right, 3 spaces.
>>> print (move('left'))
Move left, 4 spaces.
>>> print (move('down'))
Move down, 4 spaces.
>>> print (move('up'))
Move up, 3 spaces.
>>> spaces
Traceback (most recent call last):
  File "<pyshell#17>", line 1, in <module>
    spaces
NameError: name 'spaces' is not defined
>>> direction
Traceback (most recent call last):
  File "<pyshell#18>", line 1, in <module>
    direction
NameError: name 'direction' is not defined
>>>