gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 20:22:29 26 4
gpt4 key购买 nike

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

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 中 | 是二元或。您应该像这样使用 运算符

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 ,

The | operator yields the bitwise (inclusive) OR of its arguments, which must be plain or long integers. The arguments are converted to a common type.

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

if guess in (location1, location2, location3):

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

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

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

关于python - TypeError:不支持的操作数类型 |: 'int' 和 'str',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23390469/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com