gpt4 book ai didi

python - 什么是常量和文字常量?

转载 作者:太空狗 更新时间:2023-10-29 22:26:18 27 4
gpt4 key购买 nike

我正在学习 Python,我对常量和文字常量感到困惑。这些是什么?我们使用它们的目的是什么?与普通变量有什么区别?

我是一个真正的初学者。作为初学者,我可以说我对编程世界一无所知。例如,我不知道表达式是什么,反之亦然。

我一直在使用“A byte of python”这本书学习 Python 语言,在书中的某处我遇到了一个讨论文字和常量的部分。我在那里分享了该部分:

5.2. Literal Constants

An example of a literal constant is a number like 5 , 1.23 , or astring like 'This is a string' or "It's a string!" .

It is called a literal because it is literal - you use its valueliterally. The number 2 always represents itself and nothing else - itis a constant because its value cannot be changed. Hence, all theseare referred to as literal constants.

它说,“它被称为字面值,因为它是字面值——你按字面值使用它的值”,我只是不明白这部分。这本书试图说我们从字面上使用该值是什么意思?另一个模糊的地方是数字 2 是一个常数,因为它的值不能改变。这怎么可能?我们可以更改它,例如:

stack = 2
stack = 3

首先,我将数字 2 分配给堆栈,然后更改堆栈的值(即书中声称的数字 2 是一个常量,因此无法更改)并将数字 3 分配给它。所以,我很容易地改变了数字 2 的值。我真的很困惑,如果你不明白我的意思,请告诉我,这样我可以举更多的例子。

最佳答案

OP编辑后的回答

文字常量是实际的文字值;我知道文字这个词会让你感到困惑,但举个例子可能会让你更清楚。如果您在 REPL 中键入以下内容:

>>> 2
2
>>> 'hello'
'hello'

2hello 是实际的文字常量,与您的想法相反,您无法更改它们的值(好吧,您可以,作为初学者,最好不知道那件事)。当你有:

stack = 2
stack = 3

您首先将常量文字(尽管老实说,不要担心它叫什么,它是数字 2)分配给 stack。因此,名称 stack 指向值 2。然后,通过说 stack = 3,您不是更改值 2您现在使名称 stack 指向另一个值,3

就其值(value)而言,“常量文字”听起来很复杂;只需将 2'John' 等值想象成它们的本来面目。关于实际常量(在编程中,常量指的是赋值后不能更改的变量),这个概念在 Python 中并不存在。例如,一个常量是当您说 stack = 2 但您永远无法更改 stack 指向的内容时,否则您将收到错误。在 Python 中,这个概念不存在。

原答案:

对于初学者,我建议您阅读 The story of None, True and False (and an explanation of literals, keywords and builtins thrown in)通过圭多:

A literal, on the other hand, is an element of an expression that describes a constant value. Examples of literals are numbers (e.g. 42, 3.14, or 1.6e-10) and strings (e.g. "Hello, world"). Literals are recognized by the parser, and the exact rules for how literals are parsed are often quite subtle.

至于“常量”,您不能在 Python 中将变量声明为“真正的常量”。有一个Built-in Constants像 Python 中的 TrueFalseNone 但即使它们在 Python 2.X 中也不是“真正的常量”,因为它们可以分配给点到另一个值:

True = False
if True:
print 'Hey'
else:
print 'WAAAT!'

希望对您有所帮助。如果不是,请编辑您的问题并举例说明常量和文字常量的确切含义。

注意:TrueFalse 等是 Python 3.x 中的关键字,所以如果你说 True = False,解释器将引发 SyntaxError: assignment to keyword

关于python - 什么是常量和文字常量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24122798/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com