[英]What am I missing in this python? It's a simple program to order 3 terms, and the last order part doesn't work
I already tried inputting the SWAP() function directly, and it works, but with the function inside it doesn't swap the variables.我已经尝试直接输入 SWAP() 函数,它可以工作,但是它内部的函数不会交换变量。
def SWAP(x,y):
w = x
x = y
y = w
del w
def ORDER(x,y,z):
if x > z:
SWAP(x,z)
if x > y:
SWAP(x,y)
if y > z:
SWAP(y,z)
print(f'{x}<{y}<{z}')
When you are calling SWAP
function it is not returning the values.当您调用
SWAP
函数时,它不会返回值。 And function args are not sent as call-by-reference
.并且函数 args 不会作为
call-by-reference
发送。
So what ever changes you do in SWAP function does not get reflected in the calling function.因此,您在 SWAP 函数中所做的任何更改都不会反映在调用函数中。
Try this :尝试这个 :
def SWAP(x,y):
w = x
x = y
y = w
return x,y
def ORDER(x,y,z):
if x > z:
x,z=SWAP(x,z)
if x > y:
x,y=SWAP(x,y)
if y > z:
y,z=SWAP(y,z)
print(f'{x}<{y}<{z}')
Explanation :解释 :
SWAP function takes 2 args x,y
and returns the swapped value. SWAP 函数接受 2 个参数
x,y
并返回交换后的值。 Swapping done by you was correct.你做的交换是正确的。
While calling SWAP I am expecting a return of 2 variable which should be swapped.在调用 SWAP 时,我期望返回 2 个应该交换的变量。
Eg.例如。 -
——
a = 5
b = 8
a,b = SWAP(a,b)
Here I am calling SWAP with `a,b` who have values `5,8` currently,
Now SWAP returns `8,5`as response. I am storing `8,5` into `a,b`.
So Now a becomes 8 and b becomes 5.
All the other logic is same as you wrote for comparing.
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.