0

This is my code. Here if condition does not work only show else message. Help please.

var = raw_input("Please enter something: ")
if(var==10):print"equal"
else:print "not qual"
Martijn Pieters
  • 963,270
  • 265
  • 3,804
  • 3,187
Neo
  • 33
  • 1
  • 3

3 Answers3

2

raw_input() returns a string, but you are comparing that string to an integer. Python won't automatically convert between the types.

Either compare to a string:

if var == '10':

or convert var to an integer:

var = int(var)

The latter will raise a ValueError exception if var is not convertable to an integer, and you may want to handle that case. Also see Asking the user for input until they give a valid response.

Community
  • 1
  • 1
Martijn Pieters
  • 963,270
  • 265
  • 3,804
  • 3,187
0

raw_input() in Python2.x will return as string , you have to use int() to switch type:

var  = raw_input("number:")
try:
  num_var = int(var)
except ValueError:
  print "value error"

if num_var == 10:
  print 'ten'

Or you can use input() to get input a number:

>>> num = input()
100
>>> num + 1
101

If you want to use input() to get a string, you have to add something in the string :

>>> string_x = input()
'ok'
>>> string_x
'ok'
lqhcpsgbl
  • 3,526
  • 3
  • 20
  • 30
0

just use input() instead of raw_input() which will automatically evaluate the user input. Hope that helps! :)

Chris Nguyen
  • 150
  • 3
  • 14