["101011101"] is a list with a single string. "101011101" is a list of characters. Look at this:
for let_me_find_out in ["101011101"]:
print(let_me_find_out)
for let_me_find_out in "101011101":
print(let_me_find_out)
With this knowledge, you can now start your binary conversion:
for binairy in "101011101":
binairy = binairy ** 2
print(binairy)
That code gives you the error:
TypeError: unsupported operand type(s) for ** or pow(): 'str' and 'int'
It means that you have the operator ** and you put it between a string and a number. However, you can only put it between two numbers.
So you need to convert the string into a number using int():
for binairy in "101011101":
binairy = int(binairy) ** 2
print(binairy)
You'll now find that it still gives you 1s and 0s only. That is because you calculated 1^2 instead of 2^1. Swap the order of the operands:
for binairy in "101011101":
binairy = 2**int(binairy)
print(binairy)
Now you get 2s and 1s, which is still incorrect. To deal with this, remember basic school where you learned about how numbers work. You don't use the number and take it to the power of something. Let me explain:
The number 29 is not calculated by 10^2 + 1^9 (which is 101). It is calculated by 2*10^1 + 9*10^0. So your formula needs to be rewritten from scratch.
As you see, you have 3 components in a single part of the sum:
- the digit value (2 or 9 in my example, but just 0 or 1 in a binary number)
- the base (10 in my example, but 2 in your example)
- the power (starting at 0 and counting upwards)
This brings you to
power = 0
for binairy in "101011101":
digit = int(binairy)
base = 2
value = digit * base ** power
print(value)
power += 1
With above code you get the individual values, but not the total value. So you need to introduce a sum:
power = 0
sum = 0
for binairy in "101011101":
digit = int(binairy)
base = 2
value = digit * base ** power
sum += value
print(value)
power += 1
print(sum)
And you'll find that it gives you 373, which is not the correct answer (349 is correct). This is because you started the calculation from the beginning, but you should start at the end. A simple way to fix this is to reverse the text:
power = 0
sum = 0
for binairy in reversed("101011101"):
digit = int(binairy)
base = 2
value = digit * base ** power
sum += value
print(value)
power += 1
print(sum)
Bam, you get it. That was easy! Just 1 hour of coding :-)
Later in your career, feel free to write print(int("101011101", 2)) instead. Your colleagues will love you for using built-in functionality instead of writing complicated code.
binairyis a string variable and power operation doesn't support string variable as an argumentint("101011101", 2)converts the string from base 2 (and to an integer), right?int("11", 16) == 17converting from base 16, andint("11", 2) == 3converting from base 2.