Python - 实现函数

标签 python

我正在创建一个函数来检查 x 是否大于 y,如果不是,它会切换两个值并返回它们。

def xGreater(x, y):
    if(y > x):
        x, y = y, x
    return x, y

我的问题是在另一个函数中使用这个函数的最佳方式是什么,我当前的代码如下:

def gcd(x, y):
    x , y = xGreater(x, y)
    r = x % y
    while(r != 0):
        x, y = y, r
        r = x % y
    return y

我不能简单地调用 xGreater(x, y) 来改变 x 和 y 的值,而不在前面加上 x, y = 吗?或者这是否仅在返回单个变量时才有效。谢谢!

最佳答案

Can I not simply call xGreater(x, y) to alter the values of x and y, without the x, y = in front?

恐怕你不能,因为 xy 是不可变的,并且按值传递给 xGreater()

在某些特殊情况下可以这样做(例如,如果 xy 是两个列表),但一般情况下不会这样做。

老实说,我会去掉 xGreater() 并在 gcd() 中进行交换:

def gcd(x, y):
    if y > x:
        x, y = y, x
    r = x % y
    ...

我个人觉得这样代码更易读。

关于Python - 实现函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15455092/

相关文章:

python - 就地更改 Pandas 数据框列值

python - 在 NetworkX 中创建大图时出现内存错误

python - 数据框的每一行都有一个列名称..如何将其更改为一行名称?

python - 写入yaml文件: attribute error

python - 为什么使用字典测试包含比使用集合测试更快?

python - 打印当前模块名称的函数,当从另一个模块调用时也是如此

python - 禁用 SSL 证书检查 Twisted Agents

python - 在 Python 中将类文件对象添加到 Zip 文件

Python,确定是否应将字符串转换为 Int 或 Float

python - python 中的 Bokeh 库 : can I provide a custom y range in terms of values to have?