0

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 side note: in your if statement, 0 <= int(key_one) < 128 will be way more efficient than int(key_one) in range(128). Commented Jul 15, 2010 at 4:57

2 Answers 2

3

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

Sign up to request clarification or add additional context in comments.

1 Comment

No problem. Glad you figured it out.
1

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: '))

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.