12/19 why not use elif instead of else?


Below is the code of mine, i’m having trouble figuring out why using a if under the else, the elif method seems working just as fine…

if guess_row == ship_row and guess_col == ship_col:
  print "Congratulations! You sank my battleship!"  
elif guess_row not in range(5) or guess_col not in range(5):
  print ('Oops, that\'s not even in the ocean' )
  print "You missed my battleship!"
  board[guess_row][guess_col] = "X"


programming isn’t just about making the code work, its about efficient design, readability and maintainability

there are two possible scenarios after the user entered coordinates: hit or miss. in other words, if (hit) or else (miss)

its separates the logic for different scenarios better. Using elif is possible, but just making the code work isn’t good enough more in today’s world

personally, i would do it differently. But then we are going of the path of the exercise. i would do something along the lines off:

while True:
        guess_row = int(raw_input("Guess Row: "))
        guess_col = int(raw_input("Guess Col: "))
        if guess_row not in range(5) and guess_col not in range(5):
            print "Oops, that's not even in the ocean."
    except ValueError:
        print "You must enter a integer"

validate the user input first, before doing anything else. And very likely i would put that code in a function.


This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.