python - 我正在更改一个变量,但是如何在函数结束时返回它的原始状态?

标签 python python-3.x function variables

我编辑了这篇文章,以获取单词“叉总和”而不是“阶乘”,感谢您的帮助。

def assignment_2():
    # write a function that outputs the cross sum of a number (54321 -> 5 + 4 + 3 + 2 + 1 = 15)

    number = int(input('enter a number'))
    result = 0

    while number:
        result = result + number % 10
        number = int(number / I0)
    return result, number

当我调用该函数时,我得到的结果没有问题,但数字 = 0,因为它正在经历该循环。

这就是我调用该函数的方式

result, number = assignment_2()
print(f'assignment 2: the cross sum of {number} is {result}')

最佳答案

只需将值保存到另一个变量:

number = int(input('enter a number'))
orig = number
result = 0

while number:
    result = result + number % 10
    number = int(number / 10)
return result, orig

关于python - 我正在更改一个变量,但是如何在函数结束时返回它的原始状态?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53465523/

相关文章:

python - TypeError : list indices must be integers or slices, 不是电影评级数据的元组

python - 是否有一个模仿 A[[i,j],...][...,[a,b,c]] 但不是只读的 numpy 函数?

python - 对不返回值的函数使用 map()

python-3.x - 将 Pandas 数据帧转换为 utf8

excel - VBA - 在 Evaluate() 中包含自己的函数

javascript - 将两个数组传递给函数,使用数据来启动按钮按下。 JavaScript

Python分类定义特征重要性

python - 有没有办法管理列表中的 float ?

python - 仅在满足 if 条件后才运行 for 循环

python - 为 docker-compose 文件设置预 Hook