tags:

views:

47

answers:

2

I can not figure out why my code is not working,

key_one= raw_input("Enter key (0 <= key <= 127): ")

if key_one in range(128):
    bin_key_one=bin(key_one)[2:]
    print bin_key_one               
else:
    print "You have to enter key (0 <= key <= 127)"

when i enter a number between 0 and 127, it keeps on going to the else! can some one tell me why?

+1  A: 

raw_input will return a string, so your if comparison fails (you're comparing an int with a string). Try casting:

key_one = int(raw_input('enter key: '))
ars
+3  A: 

raw_input returns a string and "93" is NOT in range(128).

To make sure you compare apples to apples, cast key_one to int:

key = int(raw_input("Enter key (0 <= key <= 127): "))
if key in range(128)
   # if condition
else
   # else condition

EDIT: Python documentation is awesome, so if you have questions, it's a great idea to train by reading the docs first.

If the prompt argument is present, it is written to standard output without a trailing newline. The function then reads a line from input, converts it to a string (stripping a trailing newline), and returns that. When EOF is read, EOFError is raised. - http://docs.python.org/library/functions.html#raw_input

tjko
yep it works.. thanx man
babikar
No problem. Glad you figured it out.
tjko