[英]letter variable without being defined works in Python
My code is this: 我的代码是这样的:
word = input('enter a word:')
for letter in word:
print( letter)
Output: 输出:
enter a word:tree
t
r
e
e
Is letter
an in-built variable? letter
是内置变量吗?
You don't need to declare variables in Python. 您无需在Python中声明变量。 The variable is defined in the for-loop directly.
该变量直接在for循环中定义。 Python has only very few keywords .
Python只有很少的关键字 。 It is also not a built-in constant .
它也不是内置常量 。
I recommend going through a Python tutorial . 我建议阅读Python教程 。 You might also want to try exercism .
您可能还想尝试运动 。
The following stuff is only relevant for Python 3.6+. 以下内容仅与Python 3.6+相关。 No matter which Python version you use, you can ignore it.
无论您使用哪个Python版本,都可以忽略它。 If you are a very early beginner, you probably should ignore it.
如果您是初学者,则可能应该忽略它。
You can use variable annotations to "declare" a variable. 您可以使用变量注释来“声明”变量。 PEP 526 introduces them.
PEP 526介绍了它们。 They look like this:
他们看起来像这样:
foo: str
int: bar
Python is a language which doesn't require to declare variables beforehand, like Pascal or any versions of C. In the moment you use a new variable, it is considered as being declared. Python是不需要预先声明变量的语言,例如Pascal或C的任何版本。当您使用新变量时,它被视为已声明。 In your case,
letter
is declared in the for
loop. 在您的情况下,
letter
在for
循环中声明。
"Variables declaration"
in Python is implicit, in fact we better use name binding
. Python中的
"Variables declaration"
是隐式的,实际上我们最好使用name binding
。 There are many ways of name binding
in Python, for
is one of them. Python中的
name binding
方法有很多, for
是其中一种。
For more details, you can have a look at binding-of-names . 有关更多详细信息,您可以查看名称绑定 。
There is one very important implicit fact: Python will pre-compute all names before executing code of one certain scope. 有一个非常重要的隐性事实: Python将在执行某一范围的代码之前预先计算所有名称。
def test_1():
b = a + 1
def test_2():
b = a + 1
for a in range(3):
print(a)
# NameError: name 'a' is not defined
test_1()
# UnboundLocalError: local variable 'a' referenced before assignment
test_2()
In test_1
, when executing b = a + 1
, the error is name 'a' is not defined
. 在
test_1
,当执行b = a + 1
,错误是name 'a' is not defined
。
In test_2
, when executing b = a + 1
, the error is local variable 'a' referenced before assignment
. 在
test_2
,当执行b = a + 1
,错误是local variable 'a' referenced before assignment
。 That is to say, in test_2
, when executing b = a + 1
, Python already knew that a
is a local variable, it just has not been bound to an object, so the error is UnboundLocalError
. 也就是说,在
test_2
,当执行b = a + 1
,Python已经知道a
是局部变量,它尚未绑定到对象,因此错误是UnboundLocalError
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.