Skip to main content
 首页 » 编程设计

python之为什么在 if else block 中定义的变量可以在 block 外使用

2025年05月04日15zhengyun_ustc

import numpy as np 
import tensorflow as tf 
 
 
class simpleTest(tf.test.TestCase): 
  def setUp(self): 
    self.X = np.random.random_sample(size = (2, 3, 2)) 
 
  def test(self): 
    a = 4 
    x = tf.constant(self.X,  dtype=tf.float32) 
    if a % 2 == 0: 
      y = 2*x 
 
    else: 
      y = 3*x  
 
    z = 4*y 
 
    with self.test_session(): 
      print y.eval() 
      print z.eval() 
 
if __name__ == "__main__": 
  tf.test.main() 

这里y是tensorflow变量,定义在if else block 内,为什么可以在 block 外使用?

请您参考如下方法:

这比 更通用, 它与 有关的变量范围。记住这一点:

Python does not have a block scope!*


考虑这个简单的例子:

x = 2 
a = 5 
if a == 5: 
    y = 2 * x 
else: 
    y = 3 * x 
 
z = 4 * y 
print z     # prints 16 

我想说的是 y 不是 if 语句主体范围内定义的局部变量,因此可以在之后使用它if 语句。


更多信息:Variables_and_Scope .

<子> * Block scope in Python