[英]I'm getting a typeError: unsupported operand type(s) for -: 'str' and 'int'
[英]I'm getting a 'str' and 'int' TypeError on my bitwise program when using 'input'
這個簡單的程序檢查用戶提供的整數中的第 4 位是否打開。 您提供一個數字(例如 12),然后它將從字符串轉換為整數,然后從 base10 轉換為二進制。 但是,盡管進行了int()
和bin()
轉換,我仍然收到錯誤消息,提示&
不能用於“str”和“int”。
據我了解int()
和bin()
函數,用戶提供的數字在傳遞給check_bit4()
函數時應該是一個按位整數。 我錯過了什么?
def check_bit4(x):
check = 0b00001000
if x & check > 0:
return("on")
else:
return("off")
x = bin(int(input("Enter Integer ")))
check_bit4(x)
File "Problem3.py", line 3, in check_bit4
if x & check > 0:
TypeError: unsupported operand type(s) for &: 'str' and 'int'
沒有理由使用bin(..)
。 bin(..)
不會將整數轉換為二進制等價物,int 已經存儲為二進制。 它用 0 和 1 作為字符串構造整數的表示(一個人可以讀取的東西)。 確實:
>>> type(bin(1425))
<class 'str'>
所以你可以簡單地使用:
x = int(input("Enter Integer ")) # look ma, no bin(..)
check_bit4(x)
在你的函數中,你寫0b00001000
但這也是一個整數:如果你直接寫8
,那不會有什么區別。
嗯,這是因為bin(x)返回一個字符串
參考: https : //docs.python.org/3/library/functions.html#bin
因此,在上面的行中,您嘗試&(和)字符串和 int 導致錯誤。
所以我們需要在使用&(and)運算符之前將字符串轉換為 int。
我建議您直接在輸入數字上使用&(和)運算符,而不是這些繁瑣的任務。
def check_bit4(x):
check = 8 #decimal representation of 0b00001000
if x & check: #if condition will be true if the answer is non zero
return("on")
else:
return("off")
x = int(input("Enter Integer "))
print(check_bit4(x))
我希望這能解決您的問題:)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.