簡體   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-2025 STACKOOM.COM