Greetings once more. I have been working on a script to convert a user provided number in basetwo and convert it to baseten. What I've got so far:

``````myinput = raw_input("Enter a binary real number: ")
(myint, myfrac) = myinput.split(".")
x = int(myint[0])
y = 0
t = len(myint)
while y < (t - 1):
if y == t:
z = 0
else:
z = int(myint[y + 1])
x = x * 2 + z
y = y + 1
b = int(myfrac[-1])
k = len(myfrac)
a = 1
while a <= k:
if a == k:
c = 0
else:
c = int(myfrac[(-1 - a)])
b = b * 2 + c
a = a + 1
print myinput + " in basetwo is equivalent to %d.%d in baseten." % (x, b)``````

It seems to work, but I feel like I'm going about this the entirely wrong way ie. there is a simpler way to write this algorithm.

2
Contributors
1
2
Views
10 Years
Discussion Span
Last Post by woooee
``````while y < (t - 1):
if y == t:``````

Note that (t-1) < t, so y is always less than t and the if() portion will never be executed. You can also use a for loop

``````t = len(myint)
##while y < (t - 1):
for y in range(0, t):``````
This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.