I am a newbie on python. I have just create a program taking a 2’s complement binary number and convert it to decimal value. (The way of conversion is described at http://sandbox.mc.edu/~bennet/cs110/tc/tctod.html.)
I am aware that there are some certain rules on how to format your program and some “good habits” on how to design your program. Like how you put a header, comment, etc. And how you design the structure of it. I could not find a guide on Internet so I decide to ask here.
This is my first time making post on stackoverflow, so please bear with me if I make any mistakes. : )
Here is my code.
def secBiToDecimal(number):
""" This program takes a 2's complement binary number as input and returns its decimal value
"""
output = ""
" Check the sign of this number and calculate its value in according way."
if number[0]=='0':
output += "+"
temp = 0
for i in range(1,len(number)):
temp += (int(number[i]) * (2**(len(number)-i-1)))
output += str(temp)
print output
elif number[0]=='1':
output += "-"
carryout = 1
" flip the digits"
number = list(number)
for i in range(len(number)):
if number[i] == "1":
number[i]='0'
else:
number[i]='1'
" add 1 to number in binary sense "
for i in range(1,len(number)):
if carryout == 0 and number[len(number)-i]=='0':
break
elif carryout == 1 and number[len(number)-i]=='0':
number[len(number)-i]='1'
break
elif carryout == 0 and number[len(number)-i]=='1':
number[len(number)-i]='1'
break
elif carryout == 1 and number[len(number)-i]=='1':
number[len(number)-i]='0'
number = "".join(number)
temp = 0
for i in range(1,len(number)):
temp += int(number[i]) * (2**(len(number)-1-i))
output += str(temp)
print output
One of the most important things to consider with regard to code formatting, styling and conventions is the “house rules”. If your “house” (i.e. work place, team, school, teacher, etc.) expects things done in a certain way, then that is the way you should do it.
Standards and conventions found on the internet can be used as source material for discussions on changing the house rules, or to develop your own personal standard for personal projects.
But do use some standard, and keep an offline copy of the documentation for that standard if you can, so that you can read your own code 6, 12, 24 months down the line ;).