简体   繁体   English

我在这条蟒蛇中缺少什么? 这是一个简单的程序来订购3个术语,最后一个订购部分不起作用

[英]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.

相关问题 python merge():如果我更改数据框顺序不起作用 - python merge() : doesn't work if i change the dataframe order Python SQlite ORDER BY命令不起作用 - Python SQlite ORDER BY command doesn't work 我在这里想念什么? python 中的简单 for 循环 - What am I missing here? Simple for loop in python 这两个简单的python代码有什么区别? (一个有效,另一个无效) - what's different between these two simple python codes? (one works and the other doesn't work) python中not()的命令有什么问题? - What's wrong with order for not() in python? 我程序的解密部分不起作用 - The decryption part of my program doesn't work 我不明白为什么我不能让 python 中的 readline function 在这个程序中工作。 我究竟做错了什么? - I don't understand why i can't get readline function in python to work in this program. What am I doing wrong? 简单的Python游戏无论如何都无法正常工作 - simple Python game doesn't work no matter what Pandas df 重新排序列似乎在循环中工作,但没有。 我到底错过了什么? - Pandas df re-ordering columns seems to work within a loop, but doesn't. What the heck am I missing? 为了在Python 2.7中工作,我需要在代码中进行哪些修改? - What do I modify in the code in order for it to work in Python 2.7?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM