英文:
Changing the place of equation in Python
问题
I defined the "true" variable summing up all the t, r, u, and e integers at the first image. When I wrote t + r + u + e = true, it gave an error but when I changed their places and wrote true = t + r + u + e, it worked.
[错误在这里] (https://i.stack.imgur.com/srlWG.png)
[已修复但为什么] (https://i.stack.imgur.com/L9nm8.png)
能有人解释一下吗?
- 100天编程挑战,第3天,爱情计算器项目
英文:
I defined the "true" variable summing up all the t, r, u and e integers at the first image. When I wrote t + r + u + e = true, it gave an error but when I changed their places and wrote true = t + r + u + e, it worked.
[ERROR HERE] (https://i.stack.imgur.com/srlWG.png)
[FIXED BUT WHY] (https://i.stack.imgur.com/L9nm8.png)
Can somebody please explain?
- 100 Days of Code, Day 3, Love Calculator project
答案1
得分: 1
方程和赋值语句看起来相似,但功能不同,通过=
进行赋值,通过==
进行相等性语句区分。
赋值以变量 = 表达式
的形式出现,在表达式求值后,其值被分配给变量。你并没有将true
等同于t + r + u + e
,你是将t + r + u + e
的值赋给了true
。这有一个方向性,一些编程语言强调这一点,使用<-
代替=
(例如True <- t + r + u + e
)。
另一个很好的例子是当你想要将一个变量的值赋给另一个变量时会发生什么。
foo = 1
bar = 2
foo = bar
print(foo)
这个打印语句应该输出什么?我们将bar
赋给了foo
还是foo
赋给了bar
?如果你允许以任何方向编写赋值语句,就会引入这种歧义。
英文:
Equations and assignment statements look similar but are functionally different and are differentiated with =
for assignment and ==
for equality statements.
Assignments come in the form variable = expression
and after the expression is evaluated, its value is assigned to the variable. You are not equating true
with t + r + u + e
, you are assigning the value of t + r + u + e
to true
. There is a directionality to this and some programming languages emphasize this by using <-
instead of =
(E.g. True <- t + r + u + e
).
Another good example is what happens when you want to assign one variable's value to another.
foo = 1
bar = 2
foo = bar
print(foo)
What should this print statement output? Did we assign bar to foo or foo to bar? If you were allowed to write assignment statements in either direction, you introduce this ambiguity.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论