0

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
2
  • 1
    Why do you wrap validate in InitialiseField? Are any of the variables set defined outside these functions? Commented Mar 16, 2018 at 21:07
  • 1
    masterfloda has the right answer v to the survival question, but really this isn't an appropriate use of recursion. Just loop until you get a value entry; this will also avoid the need for nested functions. Commented Mar 16, 2018 at 21:16

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Ah yep that makes sense thank you! With regards to styling - I am aware but this project is based from some A Level specimen files provided by an exam-board, they use the incorrect styling and we are required to use it!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.