Example code - Basics

From 22101
Jump to navigation Jump to search

Decimal to Binary number converter

I am a bit unhappy about this example due to the required knowledge of binary numbers, but as such the example is great.
Youtube: Binary numbers - watch from 2:00 to 6:00
Wikipedia on binary numbers

print("This script converts whole numbers (integers) into binary.")
# Ask for user input
number = int(input("Enter a integer: "))
# Very basic input checking, not anticipating characters or strings
# Demonstrating how important proper initializing is.
if number == 0:
    binary = "0"
else:
    binary = ""
if number >= 0:
    sign = ""
    whole = number
else:
    sign = "-"
    whole = -number

# The number is divided by two until we reach zero
# the residuals are forming the binary number, from right to left
# ie. the first residual will be the last in the bin. number
# fx. 13 -> 1101 : 1*8 + 1*4 + 0*2 + 1*1
while (whole > 0):
    residual = whole % 2
    whole = int(whole / 2)
    # Adding to the left side of the string
    binary = str(residual) + binary

print("Decimal", number, "is in Binary:", sign+binary)