Yup, binary to decimal was easy. Play with the algorithm, do a little pseudocode, poke at the code a little to figure out the Python syntax (reference manual!), debug a little and poof, it works.
- binary = input(“Enter a binary number.”)
- lenBinary = len(binary)
- dec = 0
- for i in range(lenBinary): #Go through the length of the binary number.
- if binary[lenBinary-(i+1)] == “1”: #Go from right to left checking if the value is a “1”.
- dec = dec + 2**i #If a “1” convert to base 10 and add it up.
- print(“The decimal equivalent of “, binary,” base 2 is “, dec, ” base 10.”)
Undoubtedly the Python whizzes out there can snipe the heck out of it with syntax short cuts but this is what the kids will build initially. I do very few short cuts because they are often language specific. Of course now that I look at my code I think I can redo that range parameter to do some of what that if statement is doing…
There are some things in Python that really throw me off. I guess the biggest is the range object in the for statement. I keep forgetting the range is one less than the value. Of course I take a few minutes to remember that little detail. Like I said too many languages.
A comment to my last post by Bri Morrison suggested looking at Roman numeral conversions. I hate it when people make project suggestions like that. Especially good suggestions like that. Now I am going to sit and stare at the ceiling and have to figure out how to do it. As though I did not have enough things to stare at the ceiling about. So now, Roman numerals have no place value and a smaller value to the left of a bigger value means subtract…hmmm. What a strange way to have fun. Thank God I like to mountain bike and snowboard because otherwise I would live in front of this stupid computer.