BenDeagle
BenDeagle

Reputation: 21

TypeError: unsupported operand type(s) for -=: 'str' and 'float'

I've tried to write a program which converts decimal to binary and vice versa but when I try 23, it flags line 17 (answer2 -= x) as a type error.

    import math

    x = 4096
    y = ""
    z = 10
    q = 1
    final_answer = 0

    answer1 = str(input("Do you want to convert decimal into binary (1) or binary into decimal      (2)?"))
    if answer1 == "1":
        answer2 = input("What number do you want to convert to binary? It can't be larger than   4096")
        p = answer2.isdigit()
        if p:
            for i in range(13):
                if int(answer2) >= x:
                    y = y + "1"
                    answer2 -= x
                else:
                    y = y + "0"

                x /= 2

            print(y)
        elif not p:
            print("That's not a number")

I tried to convert the variables of answer2 and x to float and int but the same problem still comes up.

Upvotes: 0

Views: 396

Answers (1)

Lexpj
Lexpj

Reputation: 1083

Your variable is still a string when you apply an operation involving a numeric value. In your case, you still need to convert the variable to a float:

answer2 = float(answer2)

Furthermore, I do not know if isdigit() catches floats (involving a decimal point). This post might help out if you get stuck there: Using isdigit for floats?

Upvotes: 1

Related Questions