1

I am new to python and trying to write a binary converter. I want to know if there is a way to check if a value entered is 0 or 1.

Example:

binary = userinput

check to see if the 8 bit numbers entered by the user are all binary numbers.

dot.Py
  • 4,831
  • 4
  • 26
  • 49
Sam
  • 11
  • 1

4 Answers4

3

Try this one:

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."

Hope that's what you are looking for.

Szabolcs
  • 3,730
  • 14
  • 34
0

You can use a conditional statement while looping through all digits of the user input value to check if it's equal to 0 or 1.

Ex.:

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!")

Code Output:

>>> 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!

Now you should ask the user for input until they give a valid response, that in your case, is a user input with 8 digits.

Community
  • 1
  • 1
dot.Py
  • 4,831
  • 4
  • 26
  • 49
0

Another option, presuming that you don't want to actually create an integer and use the exception handling mechanism:

all(bit in {"0","1"} for bit in userinput)
Matthew Cole
  • 552
  • 4
  • 19
-2

Check (8 charachters and only "0" or "1") :

is_binary = bool (
        (len (str (userinput).strip ()) == 8)  
    and all (c in ("0", "1") for c in str (userinput))
    )

If you need only to check value range (0 - 0xFF) without explicit check of 8 digits then you can use the 0b prefix (similar to 0x prefix for hexadecimal) :

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)

Other helpful functions related to binaries:

>>> bin (5)
'0b101'
>>> chr (65)
'A'
>>>
>>> ord ("A")
65
>>> import struct
>>> struct.pack ("B", 65)
'A'
>>> struct.unpack ("B", "A")
(65,)
>>>
  • `eval` for this? No! – Jean-François Fabre Mar 22 '17 at 20:12
  • If you do not know the base of the number provided in variable value_str then you must use eval (Python2.x). In general this adds much more flexibility - The user can enter a number in any format. Otherwise Python will use base (or default=10) and raise a ValueError if somebody uses a different format (octal (0), hex (0x) or bin (0b)). – Zohl Martin Mar 22 '17 at 20:26
  • maybe but that is way too complicated for the question, and the second part is completely irrelevant to this question. – Jean-François Fabre Mar 22 '17 at 20:28