Search code examples
pythonpython-3.xfunctionreturn

Return values when recalling a function within a function


Working on a program that visualises the growth of plants in a field. A function is called that enter code hereeturns a value as follows:

Field = InitialiseField()

Then the function:

def InitialiseField(): #function that gives the user a choice of creating a blank field or loading a text file
  def validate():
      Response = input('Do you want to load a file with seed positions? (Y/N): ')
      if Response.upper() == 'Y':
        Field = ReadFile() #creates a multidimensional array based on an external text file
        return Field
      elif Response.upper() == 'N':
        Field = CreateNewField() #generates new field with a single seed
        return Field
      else:
          print('Please enter either N/n or Y/y')
          validate()

  return validate() #return the updated field

When a user enters a valid response (N/n or Y/y) the program continues to run as would be expected. However when a user enters an invalid response and then after enters a valid response the InitialiseField() function returns a NoneType object instead of the second response?

When a user enters an invalid response the validate() function is recalled and I am assuming it is returning the NoneType object from the first loop upon completion before the second returns the correct value - how can I resolve this?

TypeError: 'NoneType' object is not subscriptable

Solution

  • You have the answer in the title of your question :-) You need to return the value of validate():

          print('Please enter either N/n or Y/y')
          return validate()
    

    If you don't, your method does not return anything, which evaluates to is None

    Also, you might want to read the Python Styleguide: use lowercase characters for functions.