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