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!
1 Answer 1
This might happen if you get input from a file, because the string has a trailing newline. Use strip to remove it.
1 Comment
print, as suggested by Prune, would have shown the problem. This seems to be neglected in courses, but is extremely valuable to learn.
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 cascadedif.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. Perhapsinporinputstr.findfile('option b')returns'file location b'so I'm guessing it isn't actually that string.