在python中理解

2024-05-08 23:44:51 发布

您现在位置: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: "))

Tags: 功能addnumberinputvaluetypecounteranother
2条回答

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

if c:
   a = 1
print(a)

是合法的如果c是真的,那么在打印中分配的是1。如果c不是真的,那么a从未被分配,打印是一个错误。Python不像C,变量的作用域结束于变量块的末尾。如果它是一个会消失在最后的如果,但没有这样的事情发生。这是python成为动态语言的方式之一。你知道吗

借用Short Description of the Scoping Rules?Python的作用域规则非常容易记住:

  • Local任何局部范围;例如:函数
  • E封闭任何封闭范围,例如:def g():def f()
  • Global任何声明的“globals”,例如:global x
  • Bu在任何内置函数中,`。例如: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

相关问题 更多 >

    热门问题