Having trouble with if/else statements


#1



https://www.codecademy.com/en/courses/python-beginner-en-4XuFm/2/4?curriculum_id=4f89dab3d788890003000096


Whenever I input a row or column number to guess, regardless if it's within the range of the board or not, it always returns "Oops, that's not even in the ocean." I should mention that I added and modified some lines to make it a bit more interesting, so maybe that's the cause. I don't really know where the code is bugged, though, and any help would be appreciated.


Below is my code:


from random import randint

board = []

for x in range(5):
    board.append(["[]"] * 5)

def print_board(board):
    for row in board:
        print "  ".join(row)

print "Let's play Battleship!"
print_board(board)

def random_row(board):
    return randint(0, len(board) - 1)

def random_col(board):
    return randint(0, len(board[0]) - 1)

ship_row = random_row(board)
ship_col = random_col(board)

# Everything from here on should go in your for loop!
# Be sure to indent four spaces!
for turn in range(4):
    if turn==0 or turn==1 or turn==2:
        print "This is turn %d." % (turn + 1)
    if turn==3:
        print "This is turn %d, your last turn!" % (turn + 1)
    guess_row = (raw_input("Guess Row:"))
    guess_col = (raw_input("Guess Col:"))
    if guess_row.isdigit() and guess_col.isdigit():
        if guess_row == ship_row and guess_col == ship_col:
            print "Congratulations! You sunk my battleship!"
            break
        else:
            if (guess_row < 0 or guess_row > 4) or (guess_col < 0 or guess_col > 4):
                print "Oops, that's not even in the ocean."
            elif board[guess_row][guess_col] == "X":
                print "You guessed that one already."
            else:
                print "You missed my battleship!"
                board[guess_row][guess_col] = "X"
            if turn==3:
                print "Game Over."
                print "My battleship was actually at Row %d, Column %d." % (ship_row, ship_col)
    else:
        print "You have to enter numbers. Try again by clicking on the \'Save & Submit Code' button on the bottom left of the screen."
        break
print_board(board)


#2

if guess_row.isdigit() and guess_col.isdigit():

after this line you need to do the following

guess_row_int = int(guess_row)
guess_col_int = int(guess_col)

otherwise, you're still technically working with string data "2" and "3" which yes, are digits and flag isdigit() = true, but isdigit() does not cast them into integer values


#3

May we assume that you have completed the module and are now in the process of refining the program? If not, then we shouldn't be deviating from the instructions until then.

Can be written,

if turn < 3:

else:
    # last turn

Can be written:

while True:
    try:
        guess_row = int(raw_input("Guess Row:"))
        guess_col = int(raw_input("Guess Col:"))
        break
    except ValueError:
        print ("You have to enter a number.")

That covers the top segment of the loop code. Will add some more comments to this post, presently.

Consider ordering the conditions without nesting:

    if guess_row == ship_row and guess_col == ship_col:
        print "Congratulations! You sunk my battleship!"
        break
    elif guess_row not in range(5) or guess_col not in range(5):
        print "Oops, that's not even in the ocean."
        turn -= 1
    elif board[guess_row][guess_col] == "X":
        print "You guessed that one already."
        turn -= 1
    else:
        print "You missed my battleship!"
        board[guess_row][guess_col] = "X"
        print_board(board)
        if turn > 2:
            print "Game Over."
            print "My battleship was at Row %d, Column %d." % (ship_row, ship_col)

Just to clarify, turn -= 1 ensures that a turn is not wasted in either case. The user gets a 'do over'.

board.append(["O"] * 5)
print " ".join(row)

#4

Oh, ok. Thanks, I get it now. Would it be possible to somehow leave an error message programmed so that when the input is not an integer a syntax error would not appear?


#5

Thanks for the tips. It's interesting knowing there's a better (and moreover, working) alternative to what I was attempting to accomplish in my code.


#6

I've made an error in my example, regarding the turn -= 1 step. It appears Python will not let us manipulate the iterator variable, so a while loop is needed, instead.

Below is a Python 3.x version. Change the input() to raw_input() for Python 2.x.

from random import randint

board = []

for x in range(5):
    board.append(["O"] * 5)

def print_board(board):
    for row in board:
        print (" ".join(row))

print ("Let's play Battleship!")
print_board(board)

def random_row(board):
    return randint(0, len(board) - 1)

def random_col(board):
    return randint(0, len(board[0]) - 1)

ship_row = random_row(board)
ship_col = random_col(board)

turn = 0
while turn < 4:
    turn += 1
    if turn < 4:
        print ("This is turn %d." % (turn))
    else:
        print ("This is turn %d, your last turn!" % (turn))
    while True:
        try:
            guess_row = int(input("Guess Row:"))
            guess_col = int(input("Guess Col:"))
            break
        except ValueError:
            print ("You have to enter a number.")
    if guess_row == ship_row and guess_col == ship_col:
        print ("Congratulations! You sunk my battleship!")
        break
    elif guess_row not in range(5) or guess_col not in range(5):
        print ("Oops, that's not even in the ocean.")
        turn -= 1
    elif board[guess_row][guess_col] == "X":
        print ("You guessed that one already.")
        turn -= 1
    else:
        print ("You missed my battleship!")
        board[guess_row][guess_col] = "X"
        print_board(board)
        if turn > 3:
            print ("Game Over.")
            print ("My battleship is at Row %d, Column %d." % (ship_row, ship_col))

Still testing, but so far, so good.

Let's play Battleship!
O O O O O
O O O O O
O O O O O
O O O O O
O O O O O
This is turn 1.
Guess Row:5
Guess Col:5
Oops, that's not even in the ocean.
This is turn 1.
Guess Row:5
Guess Col:5
Oops, that's not even in the ocean.
This is turn 1.
Guess Row:4
Guess Col:r
You have to enter a number.
Guess Row:4
Guess Col:4
You missed my battleship!
O O O O O
O O O O O
O O O O O
O O O O O
O O O O X
This is turn 2.
Guess Row:3
Guess Col:3
You missed my battleship!
O O O O O
O O O O O
O O O O O
O O O X O
O O O O X
This is turn 3.
Guess Row:2
Guess Col:2
You missed my battleship!
O O O O O
O O O O O
O O X O O
O O O X O
O O O O X
This is turn 4, your last turn!
Guess Row:1
Guess Col:1
You missed my battleship!
O O O O O
O X O O O
O O X O O
O O O X O
O O O O X
Game Over.
My battleship was at Row 3, Column 0.
>>>

#7

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