0

my code for a random number guesser looks like so:

if answer == 'n' and 'N':
    print 'I hope to see you next time, %s' % user
    exit()

However, if I input 'N', the console blanks out and exits instead of printing the statement. 'n' works still tho and the 'Y' and 'y' statement works perfect. So I am not sure what is going on here with the 'N', but probably something simple I am overlooking. Thanks

Cachario
  • 41
  • 1
  • 1
  • 6
  • 2
    Possible duplicate of [Python's Logical Operator AND](https://stackoverflow.com/questions/18195322/pythons-logical-operator-and) and [How to test multiple variables against a value](https://stackoverflow.com/questions/15112125/how-to-test-multiple-variables-against-a-value) – pault Aug 19 '18 at 01:58
  • @pault I have no idea why it reversed the order of you two dups when I dup-hammered your close vote. Do you think it's worth editing to put them in the original order, or just leave it? – abarnert Aug 19 '18 at 02:04
  • @abarnert i think just leave it. Thanks for the hammer. – pault Aug 19 '18 at 02:08

4 Answers4

0

It's your odd syntax that is failing you.

The interpreter interprets this as

if (answer=='n') and 'N':

Note that non-empty strings are evaluated as True regardless of contents, so this is equivalent to

if (answer=='n')

To fix this, replace this line with

if answer=='n' and answer=='N':

Note that this line should never evaluate to be true.

If you want it to work, you should try

if answer=='n' or answer=='N':
Rushabh Mehta
  • 1,529
  • 1
  • 13
  • 29
0

Your statement is wrong.

First of all, when you are checking mutually exclusive inputs (in this case n or N), you must use or instead of and. and is used if you except both conditions to be met at the same time.

Secondly, you must use if answer == 'n' or answer == 'N' as your statement simply means if answer is 'n' and True as non-empty string evaluates to True.

Michal Polovka
  • 628
  • 1
  • 10
  • 21
0

You have two errors here.

First, if answer == 'n' and 'N' is not the correct way to check against two values.

In English, we can say "If the house is big or red" and we understand that "big" and "red" both refer to the house. But Python isn't like this; you have to spell out each condition explicitly, like so:

if answer == 'n' and answer == 'N':

However, even if you do this, you still have a logic error: how can answer be equal to both n and N at the same time? It can't. Use or instead of and.

John Gordon
  • 29,573
  • 7
  • 33
  • 58
0

A more succinct and pythonic way would be:

if answer in {'n', 'N'}:

You are confusing and with or. You want the print to print when either of the two conditions is met. So, you should be doing:

if answer == 'n' or answer == 'N':

Or, use the first way suggested.

Austin
  • 25,759
  • 4
  • 25
  • 48