Example code - Basics

From 22101
Revision as of 17:32, 1 March 2024 by WikiSysop (talk | contribs) (Created page with "== 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.<br> Youtube: [https://www.youtube.com/watch?v=2SUvWfNJSsM Binary numbers - watch from 2:00 to 6:00]<br> [https://en.wikipedia.org/wiki/Binary_number#Representation Wikipedia on binary numbers] <pre> print("This script converts whole numbers (integers) into binary.") # Ask for user input number = int(input("Ente...")
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
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)