[英]TypeError: unsupported operand type(s) for |: 'int' and 'str'
I tried to go through some already existing questions about my error, but none of them did the trick. 我试图解决一些有关我的错误的现有问题,但是没有一个可以解决问题。 This is the code I try to run:
这是我尝试运行的代码:
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
The error I get is: 我得到的错误是:
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'
How do I fix this? 我该如何解决?
In Python |
在Python中
|
is binary OR. 是二进制OR。 You should use
or
operator, like this 您应该像这样使用
or
运算子
if guess == location1 or guess == location2 or guess == location3:
And this line also has to be changed 而且这行也必须改变
if (guess < 0 | guess > 6):
to 至
if guess < 0 or guess > 6:
Quoting from the Binary bit-wise operator documentation , 引用Binary按位运算符文档 ,
The
|
|
operator yields the bitwise (inclusive)OR
of its arguments, which must be plain or long integers.运算符产生其参数的按位(含)
OR
,该值必须是纯整数或长整数。 The arguments are converted to a common type.参数将转换为通用类型。
But, normally this statement is written like this 但是,通常这个语句是这样写的
if guess in (location1, location2, location3):
Also, raw_input
returns a string. 另外,
raw_input
返回一个字符串。 So you need to explicitly convert that to an int
like this 所以你需要像这样将它显式转换为
int
guess = int(raw_input("Ready, aim, fire! (enter a number from 0-6): "))
Note that, you don't need ;
请注意,您不需要
;
in Python to mark the end of statement. 在Python中标记语句的结束。
You are using a binary OR operator. 您正在使用二进制OR运算符。 Just replace the "|"
只需替换“ |” with "or" and it should work fine.
与“或”,它应该可以正常工作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.