MrOHare
MrOHare

Reputation: 21

why am i getting a TypeError: unsupported operand types for %: 'NoneType and Int

I have been set a homework to convert a denary number to an 8-bit binary number. the user inputs a number and I must validate it before converting. The code works great when I enter a valid number and the validation works fine too. But, when i try an convert a number AFTER validating an invallid number, I get this NoneType operand error. Can anyone explain what I am doing wrong

def testDenary(testValue):
    if testValue < int(0):
        print("Error: Negative value input. Please try again!")
        return False
    elif testValue > 255:
        print("Error: Input value too high. Please try again!")
        return False
    else:
        return True

def getDenary():
    denIn = int(input("Please enter a number between 0 and 255: "))
    if testDenary(denIn):
        return denIn
    else:
        getDenary()

def convertToBinary(denaryIn):
    x = 0
    result = []
    for number in range(8):
        bit = denaryIn % 2
        result.append(bit)
        denaryIn = denaryIn // 2
        print (type(denaryIn))
    result.reverse()
    str1 = "".join(str(x)for x in result)
    return str1

def main():
    denary = getDenary()
    answer = convertToBinary(denary)
    print ("Binary version = " + answer)
    main()

main()

Upvotes: 2

Views: 537

Answers (1)

Steven Rumbalski
Steven Rumbalski

Reputation: 45541

Your function getDenary() does not return a value in the else-clause, so when your function ends the default return value of None is returned.

Here is how to change your code:

def getDenary():
    denIn = int(input("Please enter a number between 0 and 255: "))
    if testDenary(denIn):
        return denIn
    else:
        return getDenary() # added return

Note: You can convert an integer to its binary string representation by doing

"{0:b}".format(your_int)

Upvotes: 1

Related Questions