python - python中的变量赋值查询

标签 python variable-assignment fibonacci

我正在用 python 编写斐波那契代码。以下解决方案是我的。

enter image description here

而下面的另一个解决方案来自 python.org。

enter image description here

谁能告诉我为什么即使分配变量的逻辑相同,它也会产生不同的答案?

最佳答案

这两个程序并不等同。等号 (=) 的右侧一起计算。 正在做:

a=b
b=a+b

不同于:

a,b = b,a+b

这实际上等同于:

c = a
a = b
b = b + c

您的示例实际上包含在 Python documentation 中:

The first line contains a multiple assignment: the variables a and b simultaneously get the new values 0 and 1. On the last line this is used again, demonstrating that the expressions on the right-hand side are all evaluated first before any of the assignments take place. The right-hand side expressions are evaluated from the left to the right.

关于python - python中的变量赋值查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44766013/

相关文章:

c++ - 为什么 C++ 支持十六进制赋值,但不支持二进制赋值?如何最好地存储标志?

java - 在Java中,为什么map.get(key)[0]作为左侧有效,而map.get(key)则无效?

algorithm - 斐波那契调用堆栈中叶子与总节点的比率

java - 使用动态规划的斐波那契数列

python - 在 SymPy 中,为什么两个随机变量相加会产生难以理解的结果?

python - 在 Python 中从 unicode 字符串中去除标点符号的最快方法

vb.net - 通过属性分配给结构变量

c - 在 C 中使用共享内存的斐波那契数列

python - Python 中的列表和迭代器有什么区别?

python - 在 python 中连接列表