# 8/18 if sentence

#1

I was traing to code or sentence in other way (with if).
Something is wrong when code decrises length of string in 21.line... (First, I assumed that a is longer than b).
Could anybody make a hint how to deal with this code?

``````    s=''
for i in range(len(str(b))-2):
s+='0'
if len(str(b))==-1:
break
if str(a)[:len(str(a))]==str(b)[:len(str(b))]:
s[len(str(a))]='1'
len(a)-=1
len(b)-=1
elif str(a)[:len(str(a))]<=str(b)[:len(str(b))]:
s[len(str(a))]='1'
len(a)-=1
len(b)-=1
elif str(a)[:len(str(a))]>=str(b)[:len(str(b))]:
s[len(str(a))]='1'
len(a)-=1
len(b)-=1
else:
s[len(str(a))]='0'
len(a)-=1
len(b)-=1
return s
s=int('0b'+s)``````

#2

if str(a)[:len(str(a))]==str(b)[:len(str(b))]:
s[len(str(a))]='1'

I don't think this is right, if the decimal in a and b are equal then you add a "1" to your s. What if both decimals are "0", you will get the wrong result.

``````        len(a)-=1
len(b)-=1``````

You can't just make the string shorter by typing len(b)-=1. If you delete line 21, you will get the error on another line.

## This is a good solution:

a = 0b1110
b = 0b101
s=""

Here we find the longest binary number of the two and start a loop of that length.

length = max([len(bin(a)), len(bin(b))]) -2

for i in range(length):

We start checking from the end of the numbers by using [-1]. If either of them is equal to one, we add a "1" to our "s".

``````if bin(a)[-1]=="1" or bin(b)[-1]=="1":
s+='1'``````

We move your decimals to the right using the right shift operator. So on the next loop our "a" and "b" will become 0b111 and 0b10 respectively, and so on.

``````    a = a >> 1
b = b >> 1
else:
s+='0'
a = a >> 1
b = b >> 1``````

Because we started adding decimals to our "s" from the end of the "a" and "b", we have to reverse it to get the correct result, so we use [::-1].

s=('0b'+s[::-1])
print s

If you have any questions please ask, I will try to help.