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

2024-09-25 12:36:23 发布

您现在位置:Python中文网/ 问答频道 /正文

我试着复习一些已经存在的关于我的错误的问题,但没有一个能做到。 这是我尝试运行的代码:

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

我得到的错误是:

^{pr2}$

我怎么解决这个问题?在


Tags: fromfalsenumberif错误elseprintenter
2条回答

您使用的是二进制或运算符。只需将“|”替换为“或”就可以了。在

在Python中,|是二进制或。您应该使用or运算符,如下所示

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

这条线也必须改变

^{pr2}$

if guess < 0 or guess > 6:

引用Binary bit-wise operator documentation

^{bq}$

但是,通常这个声明是这样写的

if guess in (location1, location2, location3):

另外,raw_input返回一个字符串。所以您需要显式地将其转换为int,如下所示

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

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

相关问题 更多 >