Question

I tried to go through some already existing questions about my error, but none of them did the trick. This is the code I try to run:

from random import *

location1 = randint(0,7)
location2 = location1 + 1
location3 = location2 + 1
guess = None
hits = 0
guesses = 0
isSunk = False

while (isSunk == False):
   guess = raw_input("Ready, aim, fire! (enter a number from 0-6): ")
   if (guess < 0 | guess > 6):
      print "Please enter a valid cell number!"
   else:   
      guesses = guesses + 1;
   if (guess == location1 | guess == location2 | guess == location3):
      print "HIT!"
      hits = hits + 1
      if (hits == 3):
        isSunk = True
        print "You sank my battleship!"
      else:   
        print "MISS!"
stats = "You took " + guesses + " guesses to sink the battleship, " + "which means your shooting  accuracy was " + (3/guesses)
print stats

The error I get is:

Traceback (most recent call last):
  File "battleship.py", line 13, in <module>
    if (guess < 0 | guess > 6):
TypeError: unsupported operand type(s) for |: 'int' and 'str'

How do I fix this?

Was it helpful?

Solution

In Python | is binary OR. You should use or operator, like this

if guess == location1 or guess == location2 or guess == location3:

And this line also has to be changed

if (guess < 0 | guess > 6):

to

if guess < 0 or guess > 6:

Quoting from the Binary bit-wise operator documentation,

The | operator yields the bitwise (inclusive) OR of its arguments, which must be plain or long integers. The arguments are converted to a common type.

But, normally this statement is written like this

if guess in (location1, location2, location3):

Also, raw_input returns a string. So you need to explicitly convert that to an int like this

guess = int(raw_input("Ready, aim, fire! (enter a number from 0-6): "))

Note that, you don't need ; in Python to mark the end of statement.

OTHER TIPS

You are using a binary OR operator. Just replace the "|" with "or" and it should work fine.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top