1

I am writing a Python script for a project I am working on, and I am running into an error that I can't figure out. I am fairly new to Python, so I apologize if this is a very amateur question.

I have an if statement that is comparing a string that it got from a text file. it is supposed to take this input, then return a string with a file location depending on what the input was. However, when I run the script, it always resolves to the else clause, even when the input is exactly what it is being compared against.

def findfile(input):
     if input.lower() == 'option a':
          return 'file location a'
     elif input.lower() == 'option b':
          return 'file location b'
     elif input.lower() == 'option c':
          return 'file location c'
     elif input.lower() == 'option d':
          return 'file location d'
     else:
          return 'Invalid Input'

I have checks earlier in the script so that I know that the input being passed is a string. Regardless, even if I passed a string 'option b', it would return 'Invalid Input'.

Thanks in advance for any and all help!

4
  • There is a built-in function input() in Python. Do not use this name for your parameters or variables. Also, consider a dictionary lookup in {'option a' : 'file location a', ...} instead of the cascaded if. Commented Jan 24, 2017 at 23:42
  • 2
    Side-note: Save a little work, and perform the case conversion once, just put input = input.strip().lower() as the first line of the function, and remove the .lower() calls from each conditional test. And don't give variables the same name as Python built-ins (e.g. input) or you'll mess yourself up eventually. Perhaps inp or inputstr. Commented Jan 24, 2017 at 23:43
  • findfile('option b') returns 'file location b' so I'm guessing it isn't actually that string. Commented Jan 24, 2017 at 23:43
  • 1
    print is a cheap, but effective debugging tool. As the first statement of your function, put print "|" + input + "|", len(input). This will give you a solid idea of what you actually fed to the function. Commented Jan 24, 2017 at 23:51

1 Answer 1

2

This might happen if you get input from a file, because the string has a trailing newline. Use strip to remove it.

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

1 Comment

@JohnGredler Debugging with print, as suggested by Prune, would have shown the problem. This seems to be neglected in courses, but is extremely valuable to learn.

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.