-2

I have this script:

class usr:
  def __init__(self, inp):
    self.inp = inp
    if inp == "abc":
      print 0
      exit()


user_input = usr(raw_input())
if user_input == "123":
  print("1")
else:
  print("No")

But, even if I type "123", the output is "No". In normal circumstances I would put the "abc" statement in an if, but I need to check the input of multiple commands, so I tought that a class was the best choice.

  • It is not at all clear to me what your question is. Given that you don't implement `usr.__eq__`, how do you expect `user_input == '123'` to be evaluated sensibly? What output are you expecting from this? And why are you using old-style classes (i.e. not inheriting from `object`, despite tagging your question [tag:python-2.7])? – jonrsharpe Jan 08 '17 at 23:03
  • i do not have objects to inherit from, I suppose – Davide Fiorito Jan 08 '17 at 23:19
  • No, I mean literally from `object`. Read e.g. http://stackoverflow.com/q/54867/3001761 – jonrsharpe Jan 08 '17 at 23:22

1 Answers1

0

When data doesn't compare like you think it should, the first tool in your toolkit is the print statement. Just add print user_input and you'll find its an instance of the usr class, not the user input. You stored that in an instance variable called inp. As an aside, in pythnon 2, you should inherit from object to get a new-style class. You don't need to do that in python 3.

class usr(object):
  def __init__(self, inp):
    self.inp = inp
    if inp == "abc":
      print 0
      exit()

user_input = usr(raw_input())
if user_input.inp == "123":
  print("1")
else:
  print("No")

If all you want to do is validate the input and not store it, a function is a better option. It can just return the validated string. It can do other prettying up of the data also. In this example, I also strip whitespace from front and back so minor input errors are ignored

def usr(inp):
    inp = inp.strip()
    if inp == "abc":
      print 0
      exit()
    return inp

user_input = usr(raw_input())
if user_input == "123":
  print("1")
else:
  print("No")
tdelaney
  • 73,364
  • 6
  • 83
  • 116