Adding Input Validation
Users don't always enter what you expect. Someone might type "hello" when you ask for a number, or include spaces in a binary string. Input validation catches these problems before they crash your program.
Why Validation Matters
Without validation, your converter crashes on bad input:
Enter a decimal number: abc
Traceback (most recent call last):
ValueError: invalid literal for int() with base 10: 'abc'
That's confusing and frustrating. Good programs handle mistakes gracefully and help users correct them.
Validating Decimal Input
Use a loop with try/except to keep asking until you get valid input:
def get_decimal_input():
while True:
try:
return int(input("Enter a decimal number: "))
except ValueError:
print("Invalid input. Please enter a whole number.")
The try block attempts the conversion. If it fails, Python raises a ValueError, which the except block catches. Instead of crashing, the program prints a helpful message and loops back to ask again.
Validating Binary Input
Binary numbers should only contain 0s and 1s. Check this before attempting conversion:
def get_binary_input():
while True:
binary = input("Enter a binary number: ")
if all(c in '01' for c in binary) and binary:
return binary
print("Invalid binary. Use only 0s and 1s.")
The all() function checks that every character is either '0' or '1'. The and binary ensures the string isn't empty.
Validating Octal and Hex Input
Apply the same pattern for other bases:
def get_octal_input():
while True:
octal = input("Enter an octal number: ")
if all(c in '01234567' for c in octal) and octal:
return octal
print("Invalid octal. Use only digits 0-7.")
def get_hex_input():
while True:
hex_num = input("Enter a hex number: ").upper()
if all(c in '0123456789ABCDEF' for c in hex_num) and hex_num:
return hex_num
print("Invalid hex. Use digits 0-9 and letters A-F.")
For hexadecimal, .upper() normalizes input so users can type lowercase or uppercase letters.
Updating Your Main Loop
Replace direct input() calls with your validation functions:
elif choice == "1":
num = get_decimal_input()
print(f"Binary: {decimal_to_binary(num)}")
# ... rest of output
elif choice == "2":
binary = get_binary_input()
print(f"Decimal: {binary_to_decimal(binary)}")
Now invalid input triggers helpful messages instead of crashes.
The User Experience Difference
Before validation: program crashes, user confused.
After validation: program guides user, stays running.
This attention to edge cases separates amateur code from professional code. Your converter now handles real-world usage where people make mistakes.