Objective
Develop a Python program that prompts the user for a decimal number and displays its equivalent in binary form. It should repeat until the user enters the word "end." You must not use "str", but successive divisions.
Example Python Exercise
Show Python Code
# Repeat until the user enters the word 'end'
while True:
# Prompt the user for a decimal number or 'end' to stop
number = input("Enter a decimal number (or 'end' to stop): ")
# If the user enters 'end', break the loop
if number.lower() == 'end':
break
# Convert the input to an integer
number = int(number)
# Initialize the binary representation as an empty string
binary = ""
# Use successive divisions to convert to binary
while number > 0:
binary = str(number % 2) + binary # Add remainder (0 or 1) to binary string
number = number // 2 # Divide by 2 and discard the remainder
# If the binary string is empty (input was 0), set binary to '0'
if binary == "":
binary = "0"
# Display the binary equivalent
print(f"Binary: {binary}")
Output
Enter a decimal number (or 'end' to stop): 10
Binary: 1010
Enter a decimal number (or 'end' to stop): 255
Binary: 11111111
Enter a decimal number (or 'end' to stop): 5
Binary: 101
Enter a decimal number (or 'end' to stop): end
Share this Python Exercise