1
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()

Here y is tensorflow variable and is defined inside the if else block, why does it can be used outside the block?

gsamaras
  • 71,951
  • 46
  • 188
  • 305
Xiuyi Yang
  • 3,241
  • 5
  • 15
  • 14
  • The "blocks" in python are **only** the *function* blocks. All other statements do *not* produce a new scope. For example: `for i in range(5):pass print(i)` works, so the `i` of the `for` loop is leaked outside the loop. – Bakuriu Mar 17 '16 at 10:28

1 Answers1

6

This is more general than , it has to do with 's scope of variables. Remember this:

Python does not have a block scope!*


Consider this trivial example:

x = 2
a = 5
if a == 5:
    y = 2 * x
else:
    y = 3 * x

z = 4 * y
print z     # prints 16

What I am trying to say is that y is not a local variable defined in the scope of the body of the if statement, thus it's OK to use it after the if statement.


For more: Variables_and_Scope.

*Block scope in Python

Community
  • 1
  • 1
gsamaras
  • 71,951
  • 46
  • 188
  • 305