繁体   English   中英

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

[英]TypeError: unsupported operand type(s) for |: 'int' and 'str'

我试图解决一些有关我的错误的现有问题,但是没有一个可以解决问题。 这是我尝试运行的代码:

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'

我该如何解决?

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

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

而且这行也必须改变

if (guess < 0 | guess > 6):

if guess < 0 or guess > 6:

引用Binary按位运算符文档

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

但是,通常这个语句是这样写的

if guess in (location1, location2, location3):

另外, raw_input返回一个字符串。 所以你需要像这样将它显式转换为int

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

请注意,您不需要; 在Python中标记语句的结束。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM