Here is the problem:
number = 1101
#You may modify the lines of code above, but don't move them!
#When you Submit your code, we'll change these lines to
#assign different values to the variables.
#
#The number above represents a binary number. It will always
#be up to eight digits, and all eight digits will always be
#either 1 or 0.
#
#The string gives the binary representation of a number. In
#binary, each digit of that string corresponds to a power of
#2. The far left digit represents 128, then 64, then 32, then
#16, then 8, then 4, then 2, and then finally 1 at the far right.
#
#So, to convert the number to a decimal number, you want to (for
#example) add 128 to the total if the first digit is 1, 64 if the
#second digit is 1, 32 if the third digit is 1, etc.
#
#For example, 00001101 is the number 13: there is a 0 in the 128s
#place, 64s place, 32s place, 16s place, and 2s place. There are
#1s in the 8s, 4s, and 1s place. 8 + 4 + 1 = 13.
#
#Note that although we use 'if' a lot to describe this problem,
#this can be done entirely boolean logic and numerical comparisons.
#
#Print the number that results from this conversion.
Here is my code
##Add your code here!
number_str = str(number) # "1101"
first_num = int(number_str[-1]) * 1
#print("first num:", first_num)
second_num = int(number_str[-2]) * 2
#print("second num:", second_num)
third_num = int(number_str[-3]) * 4
#print("Third num:", third_num)
fourth_num = int(number_str[-4]) * 8
#print("fourth num:", fourth_num)
fifth_num = int(number_str[-5]) * 16
sixt_num = int(number_str[-6]) * 32
seventh_num = int(number_str[-7]) * 64
decimal = first_num + second_num + third_num + fourth_num + fifth_num + sixt_num + seventh_num
print(decimal)
The error I got was: We found a few things wrong with your code. The first one is shown below, and the rest can be found in full_results.txt in the dropdown in the top left: We tested your code with number = 1010111. We expected your code to print this: 87 However, it printed this: 7
I understand that I hard-coded this problem to accommodate 4 digits. I would like this to work for any given numbers without throwing an IndexError: string index out of range.
I appreciate your help.