1

I want to use a function to put values in a variable. But one of the parameters of this function is the parameter I want to expand. It looks like this:

X_train, y_train = load_images_to_data('a', 'data/a', X_train, y_train)

But do I have to declare the variable before this part of my program? For example typing something like

X_train
y_train

or

X_train = ( , , , )
y_train = ( , , , )

My code idea comes from here. And I wanted to change the code so I would still use de MNIST data for training but my own data for testing. But then my X_test and y_test should have an initial value.

  • Does it give you an error when you run it? Ifso then maybe you want to try something like global X_train – Thomas Mar 18 '20 at 17:05
  • 3
    In general, you don't need to *declare* a variable in Python, but if you want to pass it to a function as an argument, you must *initialize* it with something. – mkrieger1 Mar 18 '20 at 17:06
  • This line of code looks like you're _reassigning_ the variables as the output from the function, so you need to have the data assigned to the variables to pass in to the function in the first place – G. Anderson Mar 18 '20 at 17:13
  • Python doesn't have declarations, period. A variable is created the first time you assign a value to its name. – chepner Mar 18 '20 at 17:14
  • @PNX using a global variable is rarely the best solution to a problem; see [Why are global variables evil?](https://stackoverflow.com/questions/19158339/why-are-global-variables-evil) – G. Anderson Mar 18 '20 at 17:15
  • The line you show in the question takes *existing* values `X_train` and `y_train`, pass them to the function, the *reassigns* the values returned by `load_images_to_data` to those same names. The variables have to be *defined* before you can make that function call. – chepner Mar 18 '20 at 17:19
  • @G.Anderson yeah I only use global variables when I have trouble with variables and functions. Depending on the rest of Joes De Jonge's code it may be (even though I agree it's generally a bad idea) a decent idea to use global. – Thomas Mar 18 '20 at 17:20
  • Googling the code gives [this](https://blog.tanka.la/2018/10/28/build-the-mnist-model-with-your-own-handwritten-digits-using-tensorflow-keras-and-python/) tutorial. It seems that Joes de Jonge's code should initialize these variables as numpy arrays. – byrass Mar 18 '20 at 17:21

0 Answers0