在 python 期间了解

Understanding while in python

晚安,我对 while 功能有一些想法,但我想了解为什么其主体内部的变量会刷新 while 外部变量的新值 正文。 python 有什么内在的东西吗?原来是这样设计的?

    num = int(input("Type a number: "))
    while (num != 9999):
       add = 0
       counter = 0
       while (num != 0):
          add = add + num
          counter += 1
          num = int(input("Type another value: "))
       print(round(soma/contador,3))
       num = int(input("Next sequence of values. Type a number: "))

python 中的局部变量就像一个字典,每个都有最近分配的值。所以在下面的代码中:

if c:
   a = 1
print(a)

如果 c 为真则合法,a 被赋值,因此在打印中它为 1。如果 c 不为真则 a 从未被赋值并且打印是错误的。 Python 不像 C,变量的范围在变量块的末尾结束。 If it were a 会在 if 结束时消失,但不会发生这样的事情。这是 python 是一种动态语言的方式之一。

借用 Short Description of the Scoping Rules? Python 的范围规则真的很容易记住:

  • Local -- 任何本地范围;例如:函数
  • Enclosing -- 任何封闭范围,ee.g: def g(): inside def f()
  • Global -- 任何声明的 "globals",例如:global x
  • Builtin -- 任何内置函数,`.eg: max()

在您的示例代码中:(假设一个函数

def foo():
    num = int(input("Type a number: "))             # ^
    while (num != 9999):                            # |
       add = 0                                      # |
       counter = 0                                  # |
       while (num != 0):                            # |
          add = add + num                           # |
          counter += 1                              # LOCAL
          num = int(input("Type another value: "))  # |
       print(round(soma/contador,3))                # |
       num = int(                                   # |
          input((                                   # |
              "Next sequence of values. "           # |
              "Type a number: "                     # |
          ))                                        # |
       )                                            # V