0

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)
Nakul
1,32920 silver badges27 bronze badges
asked Jul 4, 2018 at 4:55
1
  • Can you quote an example here? Commented Jul 4, 2018 at 5:36

1 Answer 1

1

There are a few issues in your code.

  • Every input by default in python is taken in as 'str' , so your binaryNumber is str
  • To access an element from a list, you use[] not () as you have used here: binaryNumber(i)
  • Since your binary number is str you cant apply mathematical operations on str , so binaryNumber(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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.