1

I've just started getting into Python, but I ran into some trouble regarding user input operations. It seems that when I try to compare a raw_input to another string, it will always be false? I've made sure that case does not matter and avoided using 'input' since it will only accept numbers. After doing some googling with Python User Input, i'm pretty much confused at this point (and yes, this is for a simple temperature conversion program). I am using Python v2.7.8

TL:DR, the following code always results in the 'else' decision

mode = raw_input("Enter the type of conversion mode, C or F: ")
if (mode.lower == "c" or mode.lower == "f"): toConvert = input("Enter the number to be converted: ")
else: print mode + " is not a valid conversion type, Try again!"
3
  • As a side note: "avoided using 'input' since it will only accept numbers" is wrong; input accepts any Python expression: numbers, strings inside quotes, __import__('os').system('rm -rf /'), anything you could put in your code. But (for precisely that reason) avoiding input is a good idea anyway. Commented Oct 17, 2014 at 1:09
  • Another side note: don't try to cram as much as possible on one line; it just makes your code harder to read. Also, you don't need parentheses around if conditions in Python. Commented Oct 17, 2014 at 1:12
  • And it works! Thanks a lot guys, I thought it was simple anyhow Commented Oct 17, 2014 at 1:23

2 Answers 2

1

lower is a string method. It won't return the lower case letter unless you actually call the method which is done by parens.

Replace:

if (mode.lower == "c" or mode.lower == "f"):

With this:

if mode.lower() == "c" or mode.lower() == "f":

If you experiment with this in a python shell, you can see the difference:

>>> mode = 'C'
>>> mode.lower
<built-in method lower of str object at 0x7f7ad665e2b0>
>>> mode.lower()
'c'
Sign up to request clarification or add additional context in comments.

Comments

1

Your problem has nothing to do with raw_input, it's the next line:

if (mode.lower == "c" or mode.lower == "f"):

mode.lower is the lower method. You're asking whether that method is equal to the string "c". Of course it isn't.

What you wanted to do is call that method, and ask whether the result is equal to the string "c". Like this:

if mode.lower() == "c" or mode.lower() == "f":

Comments

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.