0

I am the new to Python. Here is a problem that I have encountered.

Assume that there is a function called set1(x).

Here is the code:

def set1(x):
    x = 1;

When I run this,

m = 5
set1(m)
m

the value of m is still 5.

So how should I code the function if I want the parameter to become 1 whenever I call the set1() function?

5gon12eder
  • 24,280
  • 5
  • 45
  • 92
Howe Chen
  • 143
  • 2
  • 12

2 Answers2

1

You can return the value

def set1():
    return 1;

And call it as

m=5
m = set1()
print (m)

It will print 1

Another way but bad method is to make it global

def set1():
    global m
    m = 1
Bhargav Rao
  • 50,140
  • 28
  • 121
  • 140
0

Functions use a local namespace in which they declare their variables, which means that in most cases when you pass an argument to a function, it will not effect the argument outside of the function (in the global namespace). So while the value changes within the function, it does not change outside of the function.

If you want the function to change the value, you need to return the value as such:

def set1(x):
    x=1
    return x


>>> m=5
>>> m = set1(m)
>>> m
1

This said, if your argument is mutable, it can change.

def set2(x):
    x[0] = 1

>>> m = [2]
>>> set2(m)
>>> m[0]
1
NDevox
  • 4,056
  • 4
  • 21
  • 36
  • 1
    _"Functions use local variables"_ - this isn't entirely true, functions _create a namespace_ which is what makes variables you define within the body "local to that function". – Burhan Khalid Jan 14 '15 at 11:47
  • @BurhanKhalid You're right. I updated the answer. – NDevox Jan 14 '15 at 11:50