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


i'm trying write function checks if given string binary or not. i'm using while loop browse characters in string 1 one. if of them 0's or 1's it's going return true, if not - break loop , return false. i've written tiny part of code, 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             continue         else:             print (count, character[count], "error")             return false             break 

edit:
tried using 'set' elude iterating loop, don't quite how "set(string)" work. got error cant consider list. how can compare elements 0 & 1?

def fnisbin(string): characterslist = set(string) if len(characterslist) > 2:     return false else:     if (characterslist[0] == '0' or characterslist[0] == '1') , (characterslist[1] == '0' or characterslist[1] == '1'): #there made error, how deal it?         return true     else:         return false 

you're printing ok each character that's 0 or 1, though there may later character isn't. need wait until end of loop know it's ok.

def fnisbin(string):     character in string:         if character != '0' , character != '1':             print (character, "error")             return false     print "ok"     return true 

there's no need break after return false -- returning function automatically breaks out of loop.


Popular posts from this blog

php - How should I create my API for mobile applications (Needs Authentication) -

5 Reasons to Blog Anonymously (and 5 Reasons Not To)

Google AdWords and AdSense - A Dynamic Small Business Marketing Duo