12/19 why not use elif instead of else?


#1

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' )
else:
  print "You missed my battleship!"
  board[guess_row][guess_col] = "X"
  print_board(board)

#2

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:
    try:
        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."
        else: 
            break
    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.


#3

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