我是python的新手并尝试编写二进制转换器。我想知道是否有办法检查输入的值是0还是1。
示例:
binary = userinput
检查用户输入的8位数字是否都是二进制数。
答案 0 :(得分:3)
试试这个:
bin_str = raw_input('Enter a binary number: ')
try:
bin_num = int(bin_str, 2)
print "Valid binary number entered. - " + bin_str
except ValueError:
print "Invalid number entered."
希望这就是你要找的东西。
答案 1 :(得分:0)
您可以在循环浏览用户输入值的所有数字时使用条件语句来检查它是否等于0或1.
例:
num = str(input("Insert binary number: "))
for n in num:
if n == "0" or n == "1":
print(n, "is a binary digit!")
else:
print(n, "is not a binary digit!")
代码输出:
>>> Insert binary number: 12010104
>>> 1 is a binary digit!
>>> 2 is not a binary digit!
>>> 0 is a binary digit!
>>> 1 is a binary digit!
>>> 0 is a binary digit!
>>> 1 is a binary digit!
>>> 0 is a binary digit!
>>> 4 is not a binary digit!
现在你应该ask the user for input until they give a valid response,在你的情况下,是8位数的用户输入。
答案 2 :(得分:0)
另一种选择,假设您不想实际创建整数并使用异常处理机制:
all(bit in {"0","1"} for bit in userinput)
答案 3 :(得分:-2)
检查(8个字符,仅“0”或“1”):
is_binary = bool (
(len (str (userinput).strip ()) == 8)
and all (c in ("0", "1") for c in str (userinput))
)
如果只需检查值范围(0 - 0xFF)而不显式检查8位数,则可以使用0b
前缀(类似于0x
前缀的十六进制):
try:
value_str = "0b%s" % userinput
value_int = int (eval (str (value_str)))
if value_int >= 0 and value_int <= 0xFF :
is_binary = True
else :
is_binary = False
except Exception, e :
is_binary = False
# print "%s %s" % (e.__class__.__name__, e)
与二进制文件相关的其他有用功能:
>>> bin (5)
'0b101'
>>> chr (65)
'A'
>>>
>>> ord ("A")
65
>>> import struct
>>> struct.pack ("B", 65)
'A'
>>> struct.unpack ("B", "A")
(65,)
>>>