TypeError:|:' int'不支持的操作数类型和' str'

时间:2014-04-30 14:10:49

标签: python python-2.7 typeerror

我试图解决一些已经存在的关于我的错误的问题,但他们都没有做到这一点。 这是我尝试运行的代码:

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

我得到的错误是:

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'

我该如何解决这个问题?

2 个答案:

答案 0 :(得分:6)

在Python |中是二进制OR。您应该使用or运算符,就像这样

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

这条线也必须改变

if (guess < 0 | guess > 6):

if guess < 0 or guess > 6:

引自Binary bit-wise operator documentation

  

|运算符产生其参数的按位(包含)OR,它必须是普通或长整数。参数将转换为通用类型。

但是,通常这句话就是这样写的

if guess in (location1, location2, location3):

此外,raw_input返回一个字符串。所以你需要明确地将它转换为像这样的int

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

请注意,Python中不需要;来标记语句的结尾。

答案 1 :(得分:0)

您正在使用二进制OR运算符。只需更换“|”用“或”,它应该可以正常工作。