没有定义的字母变量在Python中有效

时间:2019-06-22 09:28:29

标签: python

我的代码是这样的:

word = input('enter a word:')
for letter in word:
        print( letter)

输出:

enter a word:tree
t
r
e
e

letter是内置变量吗?

3 个答案:

答案 0 :(得分:1)

您不需要在Python中声明变量。该变量直接在for循环中定义。 Python只有很少的keywords。它也不是built-in constant

我建议您通过Python tutorial。您可能还想尝试exercism

变量注释

以下内容仅与Python 3.6+相关。无论您使用哪个Python版本,都可以忽略它。如果您是初学者,则可能应该忽略它。

您可以使用变量注释来“声明”变量。 PEP 526介绍了它们。他们看起来像这样:

foo: str
int: bar

答案 1 :(得分:0)

Python是一种不需要预先声明变量的语言,例如Pascal或C的任何版本。当您使用新变量时,它被视为已声明。对于您来说,letterfor循环中声明。

答案 2 :(得分:0)

Python中的

"Variables declaration"是隐式的,实际上我们最好使用name binding。 Python中的name binding有很多方法,for是其中一种。

有关更多详细信息,请查看binding-of-names

有一个非常重要的隐性事实: 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()

test_1中,执行b = a + 1时错误为name 'a' is not defined

test_2中,执行b = a + 1时错误为local variable 'a' referenced before assignment。也就是说,在test_2中,当执行b = a + 1时,Python已经知道a是局部变量,它尚未绑定到对象,因此错误为{{ 1}}。