Help me please | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Help me please

Why isn’t this code giving me the output of 10 5? def swap(x, y): x, y = y, x x = 5 y = 10 swap(x, y) print(x, y)

11th Aug 2021, 2:05 PM
Jenkins
5 Answers
+ 3
May be new values of x ,y in function are considered "local veriable" values thus out of func. They print global values of x,y 👍
11th Aug 2021, 2:22 PM
Yash Wable 🇮🇳
Yash Wable 🇮🇳 - avatar
+ 3
You already know how to swap <x> and <y> as seen in the swap function x, y = y, x Then what's the point of making a swap function? You can do def swap(): global x, y x, y = y, x But even this still looks redundant since you know how Python swaps objects' data.
11th Aug 2021, 2:22 PM
Ipang
+ 2
Always do dry run before compiling your code on ide I don't know python much more i tried this def swap(x, y): x, y = y, x print(x,y) x = 5 y = 10 swap(x, y) print(x, y)
11th Aug 2021, 2:10 PM
A S Raghuvanshi
A S Raghuvanshi - avatar
+ 1
def swap(x,y): x,y=y,x return x,y print(swap(5,10)) Try this
11th Aug 2021, 2:17 PM
raithu
raithu - avatar
+ 1
Jenkins You have passed arguments as a value not as a reference that's why result is same. I have done like this: https://code.sololearn.com/cBWghV5r0KBl/?ref=app
11th Aug 2021, 2:54 PM
A͢J
A͢J - avatar