1

I am learning Python by trying to code up a simple adventure game. I have created a while loop to get a choice of direction from the user and I am clearly not doing it in an efficient way. I have created a while loop with multiple 'or' conditions to keep looping until the user provides one of the four valid directions as input. Unfortunately this extends the line beyond 80 characters with the tab. What is the best way to either break this line onto two lines so as not to get a syntax error or write this sort of loop more efficiently?

while direction != "N" or direction != "S" or direction != "E" or direction != "W":
    if direction == "N":
        print "You went N to the Mountain Pass"
        return 'mountain'

    elif direction == "S":
        print "You went S to the Shire"
        return 'shire'

    elif direction == ...

When I try to break the first line into two, no matter where I break it I get a syntax error...

  File "sct_game1.py", line 71
  while direction != "N" or direction != "S" or 
                                             ^
SyntaxError: invalid syntax

I'm open to suggestions on how to break the line successfully, or even better, writing this loop more efficiently.

Thanks.

sctoy
  • 37
  • 6
  • You can use `\\` at the end of the first line to make the second line continue from the first. Having said that, your while will always be True. – Morgan Thrapp Nov 04 '16 at 15:07
  • Check your `while` conditions. If the first one is false, the loop will already continue. That said, I don't understand what the `while` is supposed to do. Are you sure you don't want to test the exact opposite? – Jongware Nov 04 '16 at 15:07
  • @MorganThrapp thanks for that. Should have known that one as I have learned it but clearly not yet cemented in the noodle. – sctoy Nov 04 '16 at 16:48
  • @RadLexus what I am trying to accomplish is to take in some input from the user. If the input is anything other than 'N', 'S', 'E' or 'W' {I used upper() to deal with lowercase entries} it will keep asking for the appropriate input. My final else statement is: else: print "That's not an option. Try again." direction = raw_input("N, S, E or W? ") – sctoy Nov 04 '16 at 16:50

1 Answers1

-2

Try this:

while (direction != "N" or
        direction != "S" or
        direction != "E" or
        direction != "W"):
    # ... your code ...

Or better:

while direction not in ("N", "S", "E", "W"):
A. Jesse Jiryu Davis
  • 23,641
  • 4
  • 57
  • 70
  • 1
    `direction not in ("N", "S", "E", "W")` does something completely different. (It's probably what OP is trying to do, but not what they're doing.) – Morgan Thrapp Nov 04 '16 at 15:09
  • A. Jesse thanks. The first option worked but the second option did not and gave me an attribute error. – sctoy Nov 04 '16 at 16:45