bansheemon bansheemon - 1 year ago 79
Python Question

Python, checking if string consists only of 1's and 0's

I'm trying to write a function that checks if given string is binary or not. I'm using a while loop to browse characters in string one by one. If all of them are 0's or 1's it's going to return True, if anyone is something another - break the loop and return False.
I've just written this tiny part of code, but it doesn't run. Why?

def fnIsBin(string):
count = 0
while count < len(string):
character = string[count]
if character == '0' or character == '1':
print (count, character[count], "OK")
count = count+1
print (count, character[count], "ERROR")
return False

Answer Source

You're printing OK for each character that's 0 or 1, even though there may be a later character that isn't. You need to wait until the end of the loop to know that it's really OK.

def fnIsBin(string):
    for character in string:
        if character != '0' and character != '1':
            print (character, "ERROR")
            return False
    print "OK"
    return True

There's no need for break after return False -- returning from the function automatically breaks out of the loop.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download