Would anyone know the code in python that prints ONLY if it's a binary string?

Question:

The real problem is there:
write a program that takes a string as input and prints “Binary Number” if the string contains only 0s or 1s. Otherwise, print “Not a Binary Number”.

Asked By: FAOZIA ISLAM

||

Answers:

def check_if_binary(string) :

    p = set(string)
    s = {'0', '1'}

    if s == p or p == {'0'} or p == {'1'}:
        print("Binary Number")
    else :
        print("Not a Binary Number")

 string =  str(input ("Enter the sting : "))
 check_if_binary(string)

References: https://www.geeksforgeeks.org/python-check-if-a-given-string-is-binary-string-or-not/

Answered By: Mazid

It is easy.

def is_binary(string_to_check:str):
    for x in string_to_check: #loop though all letter
        if x in ('0','1'):
            continue #yep the letter is binary thingy
        else:
            return False #no
    return True #yep the string is binary

Next time check google before ask.

Answered By: BrainFl

You can iterate every character of the input and verify it is a zero or a one. The all function can be used for this iteration and check.

Also require that the string has at least one character:

def isBinary(string):
    return all(ch in "01" for ch in string) and string != ''

Example use:

string = input("Enter a binary number: ")
if isBinary(string):
    print("Thank you!")
else:
    print("That is not a binary number.")
Answered By: trincot
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.