-1

I have set up a script to say something when the user enters something other than Yes. However it still says this when the user says Yes. What am I doing wrong?

I am using Python 2.7.2.
Here is my code:

print 'Hi! Welcome!'
begin = raw_input ('Will you answer some questions for me? ')
if begin == 'yes':
    print 'Ok! Let\'s get started then!'
else:
    print 'Well then why did you open a script clearly entiled\'QUIZ\'?!'
Nikana Reklawyks
  • 3,233
  • 3
  • 33
  • 49
Ryan Werner
  • 177
  • 3
  • 5
  • 13

3 Answers3

6

Just change the line

if begin == 'yes':

to

if begin.lower() == 'yes':

Because string compare is case sensitive, the match will only if true iff user enters the reply in lower case

Abhijit
  • 62,056
  • 18
  • 131
  • 204
  • @Lattyware: Do you see the difference in the posted time? – Abhijit Apr 08 '12 at 11:48
  • SO normally warns me when an answer has been posted as I am writing mine, so I presumed you would have seen that warning. – Gareth Latty Apr 08 '12 at 11:48
  • @Lattyware: Your first post was the first three lines. If you disagree now, its difficult to prove :-) – Abhijit Apr 08 '12 at 11:49
  • 1
    Ah, this is true - I do the whole post then edit in the links and formatting bit too much now to think about it. My apologies. – Gareth Latty Apr 08 '12 at 11:51
  • Guys, it's not "difficult to prove": If you're not sure who was first in the future, you can check the edit history by clicking on the modification time, e.g., `edited 2 hours ago` – alexis Apr 08 '12 at 13:58
  • @alexis Actually, it is. I edited mine within the grace period of 5 minutes (IIRC), so it doesn't get added as another edit. – Gareth Latty Apr 08 '12 at 22:49
  • Oops, sorry. Hadn't realized that. – alexis Apr 09 '12 at 09:58
5

The issue here is case sensitivity.

>>> "yes" == "Yes"
False

Try using str.lower() on the user input before your comparison to ignore case. E.g:

print 'Hi! Welcome!'
begin = raw_input ('Will you answer some questions for me? ')
if begin.lower() == 'yes':
    print 'Ok! Let\'s get started then!'
else:
    print "Well then why did you open a script clearly entiled\'QUIZ\'?!"

#If a single apostrophe is used inside the print str then it must be surrounded by double apostrophes.

Community
  • 1
  • 1
Gareth Latty
  • 86,389
  • 17
  • 178
  • 183
0

Abhijit's method also works if you just want to accept more than one version of a string from a user. For example, I'm using this to confirm whether the user wants to exit:

confirm = input('Are you sure you would like to exit? N to re-run program')
  if confirm.lower() in ('n','no'): #.lower just forces the users input to be changed to lower case
    print("I'll take that as a no.")
    return confirm #this then just goes back to main()
  else:
    exit()

This way either 'n' or 'N'; 'no' or 'NO' or 'nO' are all accepted cases of 'no'.

MicahT
  • 383
  • 3
  • 6