【问题标题】:TypeError: unsupported operand type(s) for |: 'int' and 'str'类型错误:| 不支持的操作数类型:“int”和“str”
【发布时间】:2014-06-16 21:56:40
【问题描述】:

我试图解决一些已经存在的关于我的错误的问题,但没有一个能解决问题。 这是我尝试运行的代码:

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'

我该如何解决这个问题?

【问题讨论】:

  • raw_input() 返回一个 str 并且您正在与 int 进行比较。虽然这不会导致错误,但这不是您想要的。

标签: python python-2.7 typeerror


【解决方案1】:

在 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 中不需要; 来标记语句的结束。

【讨论】:

  • @user3402353 很高兴能帮上忙。如果你觉得我的回答对你有帮助,你可以Accept my Answer :-)
【解决方案2】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-05
    • 1970-01-01
    • 2017-05-27
    • 2013-10-12
    • 2014-08-10
    相关资源
    最近更新 更多