python - Why variable defined in a if else blocks can be used outside blocks? -


import numpy np import tensorflow tf   class simpletest(tf.test.testcase):   def setup(self):     self.x = np.random.random_sample(size = (2, 3, 2))    def test(self):     = 4     x = tf.constant(self.x,  dtype=tf.float32)     if % 2 == 0:       y = 2*x      else:       y = 3*x       z = 4*y      self.test_session():       print y.eval()       print z.eval()  if __name__ == "__main__":   tf.test.main() 

here y tensorflow variable , defined inside if else block, why can used outside block?

this more general , has 's scope of variables. remember this:

python does not have block scope!*


consider trivial example:

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

what trying y not local variable defined in scope of body of if statement, it's ok use after if statement.


for more: variables_and_scope.

*block scope in python


Comments

Popular posts from this blog

java - Run spring boot application error: Cannot instantiate interface org.springframework.context.ApplicationListener -

reactjs - React router and this.props.children - how to pass state to this.props.children -

Excel VBA "Microsoft Windows Common Controls 6.0 (SP6)" Location Changes -