michaelaomahony
michaelaomahony

Reputation: 13

IF OR logic statement not working as intended

while True:
    binaryStr=input('Enter binary bit pattern to be converted: ')
    binaryStrLen=len(binaryStr)
    if binaryStrLen == 8:
        pass
    elif binaryStrLen != 8:
        raise Exception('Bit pattern must be 8 values long!')
    binaryStrList=list(binaryStr)
    for i in range(8):
        if int(binaryStrList[i]) != 0 or int(binaryStrList[i]) != 1:
            print(binaryStrList[i])
            raise Exception('Non base-2 value entered!')
        elif int(binaryStrList[i]) == 0 or int(binaryStrList[i]) == 1:
            print(binaryStrList[i])
            pass

More specifically within the for loop, these if statements always return the exception even when 0s and 1s are inputted into the binaryStr variable. Is there any other way of doing this or can someone help me with this? Thanks in advance.

Upvotes: 1

Views: 64

Answers (1)

cs95
cs95

Reputation: 402283

Yes, there are issues with your conditional statements. You want to raise an exception if there are any invalid bits in your string, so you'd want something like:

if int(binaryStrList[i]) not in {0, 1}:
    ... # raise Exception

However, to simplify things, you can use regex. You can also combine your length and content checks into a single if statement.

import re
binaryStrList = ...
if len(binaryStrList) != 8 or re.search('[^01]', binaryStrList):
    raise Exception('Invalid string found')

As a side note, this code:

if something:
    pass
elif somethingElse:
    ... # do something else

Should be re-written as:

if somethingElse:
    ... # do something else

It's better coding practice, and leads to clearer, more readable code.

Upvotes: 2

Related Questions