Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.")
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading