-1

I found this code in CodeChef twitter https://twitter.com/codechef/status/941329495046459395 . It was written in C. I did it in Python3. Here is my code:

def vegas(a,b):
    temp = a
    a = b
    b = temp
a = 6
b = 9
print(a,b)
vegas(a,b)
print(a,b)

And this is the answer:

6 9
6 9

My question is, why my 'vegas' function is not swapping the value of variable 'a' and 'b'

marco.m
  • 4,573
  • 2
  • 26
  • 41
Protul
  • 95
  • 1
  • 7
  • 1
    Try adding a return statement. https://www.tutorialspoint.com/python/python_functions.htm – kometen Dec 16 '17 at 08:53
  • In your vegas function put `return a,b` and the end and then use `print(vegas(a,b))` – Sohaib Farooqi Dec 16 '17 at 08:54
  • 1
    Possible duplicate of [Function to change values of variables](https://stackoverflow.com/questions/27462805/function-to-change-values-of-variables) – JJJ Dec 16 '17 at 08:56

3 Answers3

2

It won't work the way you intend it for work. This question is answering this in full. In short: Python turns the arguments a and b into two variables which are only visible in vegas. They are initiated with the values of a and b but then have no relation to the outside a and b variables.

To make your code work, do this:

def vegas(a,b):
    temp = a
    a = b
    b = temp
    return a,b
a = 6
b = 9
print(a,b)
a,b = vegas(a,b)
print(a,b)

Also, you might be interested to know that you can swap two values with a,b = b,a

hansaplast
  • 11,007
  • 2
  • 61
  • 75
1

Yes and no... The function vegas do the work but never returns a and b so a and b still 6 and 9 outside. Arguments are passed by assignment in Python.

You can see more here

Ciro Spaciari
  • 630
  • 5
  • 10
  • 1
    This is not correct. The passing **is** by reference, but the reference is just a pointer to the value 6 and 9, and python creates new variables which are just visible inside the scope of the function. I had this wrong in a Google interview, that's why I learned this the hard way.. :) – hansaplast Dec 16 '17 at 09:02
  • 1
    That is right arguments are passed by assignment in Python. but my link is correct. i edited my answer. – Ciro Spaciari Dec 16 '17 at 09:10
1

This code snippet is a joke that "what happens in vegas stays in vegas" because the function doesn't affect the values of the variables. To affects the values, the function needs to return the result of the swap. Without a return statement, the function will not affect variables since the function creates its own temporary variables to be used within the function.