3

So, I'm building up a simple game in Python to get more acquainted with the language, and couldn't find a way of searching if this was asked before. :P Any-way, when this code block executes, I always end up with my "Position" being .y +10. I've rearanged and checked a couple things, but feel I'm missing a quite basic part of what I would normally handle with a switch statement

mv = input('N,S,E,W?')

if mv == 'N' or 'n':
    Me.Position.Y += 10    
elif mv == 'E' or 'e':
    Me.Position.X += 10    
elif mv == 'W' or 'w':
    Me.Position.X -= 10    
elif mv == 'S' or 's':
    Me.Position.Y -= 10
else:
    print('Stand')

and then:

print('Lage: X:', Me.Position.X, ' Y:', Me.Position.Y, ' Z:', Me.Position.Z)

with no way of my other options being used.

THANKS!

  • 2
    This question came up a hundred times already, yet I still fail to find one to mark as duplicate. Stupid unsearchable issue. –  Apr 12 '13 at 22:13
  • 1
    @delnan - here you go... :) - [a](http://stackoverflow.com/questions/13305089/issues-with-a-if-else-loop-in-python?rq=1) [few](http://stackoverflow.com/questions/14173108/python-if-elif-else-usage-and-clarification?rq=1) [more](http://stackoverflow.com/questions/15329646/python-program-error-elif-else-if?rq=1) [similar](http://stackoverflow.com/questions/15348879/if-else-statment-not-following-the-elif-correctly?rq=1) – mata Apr 12 '13 at 22:26

3 Answers3

11

Your code is being interpreted a little differently than what you expect. This line:

if mv == 'N' or 'n':

Is being interpreted as:

if (mv == 'N') or ('n'):

'n' is truthy, so your if statement will always be True. You have to be more explicit:

if mv == 'N' or mv == 'n':

Or use in:

if mv in ['N', 'n']:

Or use .lower():

if mv.lower() == 'n':
Blender
  • 289,723
  • 53
  • 439
  • 496
4

The problem is the or in your if-statement:

even if mv == 'N' evaluates to False, the non-empty string 'n' evaluates to True, such that mv == 'N' or 'n' is always True.

What you want is:

if mv in ['n', 'N']:
    Me.Position.Y += 10

or even just:

if mv in 'nN':
    Me.Position.Y += 10
Elmar Peise
  • 14,014
  • 3
  • 21
  • 40
  • 1
    ah, so perhaps mv == 'N' or mv == 'n' would have been better, but thank you for the even more succinct answer :D – naMretupmoC Apr 12 '13 at 22:26
2

A better approach would be to check if your answer is in a tuple of possible answers, i.e.,

In [1]: mv in ('n', 'N')
Out[1]: True

tuple is preferred since it's immutable.

However, if you want to stick with your original code, you want to use

 if mv == 'N' or mv == 'n':

because given

 mv ='n'

then

In [2]: mv == 'n'
Out[2]: True

In [3]: mv == 'N'
Out[3]: False

In [4]: mv == 'N' or 'n'
Out[4]: 'n'

but

In [5]: mv == 'n' or mv == 'N'
Out[5]: True

which is what I believe your original intent was.

Levon
  • 138,105
  • 33
  • 200
  • 191