How to print two 'if' statement in Python?

python

#1

Hello

I want to know how to print two if statements using ‘and’ operator in Python. I am not sure if I am writing the correct syntax. Below is the code:

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)
guess_row = int(raw_input(“Guess Row:”))
guess_col = int(raw_input(“Guess Col:”))

print ship_row
print ship_col

if guess_row = ship_row and guess_col = ship_col
print “Congratulation! You sank my battleship”

P.S - Check the last two lines. I am struggling there only.


#2

@Jaskey12,

If I am not wrong this problem is from code academy. In your code there is bugs related to identation, colon is missing, comparision operator and variable name not defined. Let’s look at these one by one:

  • board is not defined in your program
  • identation error with function definition and conditional statement
def random_row(board):
return randint(0, len(board) - 1)
def random_col(board):
return randint(0, len(board[0]) - 1)
if guess_row = ship_row and guess_col = ship_col
print "Congratulation! You sank my battleship"
  • Colon missing at the end of if statement and used = as a comparison operator, it should be ==.
if guess_row = ship_row and guess_col = ship_col
print "Congratulation! You sank my battleship"

Below is program that will work for you.

from random import randint

board = []

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

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)
guess_row = int(raw_input("Guess Row:"))
guess_col = int(raw_input("Guess Col:"))


if guess_row == ship_row and guess_col == ship_col:
    print "Congratulations! You sank my battleship!"
else:
    print "You missed my battleship!"

Hope this helps!

Regards,
Sunil