Hi I'm new to programming and have a project to create a program to convert binary to decimal in Python. I have to make use of the values stored in the list and multiply based on user input. I keep getting errors regarding int/str.
Any help would be appreciated.Please see code below of what I have so far.
denaryNumber = 0
binaryNumber = input("Please enter binary number: ")
placeValues = [128, 64, 32, 16, 8, 4, 2, 1]
for i in range(0, len(binaryNumber) -1):
denaryNumber = denaryNumber + (binaryNumber(i) * placeValues[i])
print (denaryNumber)
-
Can you quote an example here?user7422128– user74221282018年07月04日 05:36:50 +00:00Commented Jul 4, 2018 at 5:36
1 Answer 1
There are a few issues in your code.
- Every input by default in python is taken in as
'str', so yourbinaryNumberis str - To access an element from a list, you use
[]not()as you have used here:binaryNumber(i) - Since your binary number is
stryou cant apply mathematical operations onstr, sobinaryNumber(i) * placeValues[i]is invalid. You need to type-cast str to int like this :int(binaryNumber[i])
So change your 2nd last line to this:
denaryNumber = denaryNumber + (int(binaryNumber[i]) * placeValues[i])
It would work then.
jbtw, your code would return correct results only if your input is 8bits.
answered Jul 4, 2018 at 5:23
hsnsd
1,8231 gold badge21 silver badges36 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
lang-py