Tsunn Tsunn - 4 months ago 6
Python Question

Python passing arguments - a confused beginner

I made a quick script below to test some behaviors after encountering a problem on a larger self learning initiative. I am using python 2.7.x.

#!/usr/bin/python
def test(arg1):
y = arg1 * arg1
print 'Inside the function', y
return y

y = int(raw_input('Enter: '))
test(y)
print 'Outside the function', y



Enter: 6

Inside the function 36

Outside the function 6


However, when the code is as below:

#!/usr/bin/python
def test(arg1):
y = arg1 * arg1
print 'Inside the function', y
return y

y = test(6)
print 'Outside the function', y



Inside the function 36

Outside the function 36


Why does the first code snippet provide 36, 6 and not 36, 36 as in the second case? What suggestions can you make for the function to return the altered value (in this case 36) so that value can be passed into another function.

For context, what I am aiming to do is have the user input a value, send that value to a function. I want that function to perform some logic upon that input, for example test to make sure it meets a certain condition: uses characters [a-zA-z -], then return that value, so that it can be passed to another function. However, I am not asking for support in this

Many thanks for your time, any help is greatly appreciated.

Answer

case #1 explained

#!/usr/bin/python
def test(arg1):
    y = arg1 * arg1
    print 'Inside the function', y
    return  y; # returning 36


y=int(raw_input('Enter: ')) # here y is 6 as you read from user
test(y) # you are passing 6 and which computes y to be 36, though test is returning 36, but it is not stored in any variable (including y). (not re-assigned, so outside the definition/fucntion, y is still 6)
print 'Outside the function', y # so it is still 6

Case #2 explained

#!/usr/bin/python
def test(arg1):
    y = arg1 * arg1
    print 'Inside the function', y
    return  y; # returning 36


y=test(6) # here you received and stored it in y
print 'Outside the function', y # now y is 36
Comments