user791194
user791194

Reputation: 55

`choice == 1` is False even when user enters "1"

I am starting to learn python. I have gone through several tutorials and now I am trying to write my first script. It is a simple console menu. I am running Python 2.6.5 under cygwin.

Here is my script:

import sys

print "********************************************************************"
print "**  1) This is menu choice #1                                     **"
print "**                                                                **"
print "**                                                                **"
print "**                                                                **"
print "**                                                                **"
print "**                                                                **"
print "********************************************************************"
print
print "Choice ?"

choice = sys.stdin.readline()

print "You entered: " + choice

if choice == 1:
    choice1 = sys.stdin.readline()
    print "You entered:" + choice1
else:
    quit()

print "Exiting"

When I run the script, I get to the Choice? prompt. I enter 1 and I get the "You entered:" message and then the script exits without displaying the "Exiting" message.

Seems like it should be so easy. Thanks in advance for any help.

Upvotes: 1

Views: 370

Answers (6)

Keith
Keith

Reputation: 43024

It's exiting by calling quit() since it takes the else branch. That's because '1' (a string) does not equal 1, an integer.

Upvotes: 0

Vader
Vader

Reputation: 3873

  1. Use raw_input() instead of sys.stdin.readline()
  2. Change choice == 1 to choice == '1'

Upvotes: 2

Jeremy
Jeremy

Reputation: 5435

Not sure, but I think the user is entering a string, not a number. The number 1 and the string 1 are two completely different things.

Try choice == "1"

Upvotes: 1

Fred Larson
Fred Larson

Reputation: 62063

You're comparing a string to an integer. Try converting the string into an integer:

if int(choice.strip()) == 1:

Upvotes: 3

NPE
NPE

Reputation: 500317

The problem is that readline returns a string, but your if statement expects an int. To convert the string to an int, you could use int(choice.strip()) (be prepared for it to raise an exception if what you enter isn't a valid number).

In [8]: choice
Out[8]: '1\n'

In [9]: int(choice.strip())
Out[9]: 1

Upvotes: 1

user2100815
user2100815

Reputation:

The readline function retains the newline at the end of the input. Your first if should be:

if choice == "1\n":

assuming you want the newline.

Upvotes: 0

Related Questions