(Decimal to hex) Write a program that prompts the user to enter an integer between 0 and 15 and displays its corresponding hex number. Here are some sample runs:
Enter a decimal value (0 to 15): 11
The hex value is B
Enter a decimal value (0 to 15): 5
The hex value is 5
Enter a decimal value (0 to 15): 31
Invalid input
Program code:
#Function 'decimalToHex' to convert a decimal number
#into a hex number.
def decimalToHex(decimal):
if decimal < 10:
return str(decimal) # Return the decimal value as a string if it is less than 10
elif decimal == 10:
return 'A'
elif decimal == 11:
return 'B'
elif decimal == 12:
return 'C'
elif decimal == 13:
return 'D'
elif decimal == 14:
return 'E'
elif decimal == 15:
return 'F'
else:
return None # Return None for invalid inputs
# Prompt the user to enter a decimal value between 0 and 15
decimal = int(input("Enter a decimal value (0 to 15): "))
# Convert the decimal value to hex
hexValue = decimalToHex(decimal)
# Display the result
if hexValue is not None:
print("The hex value is", hexValue)
else:
print("Invalid input")
Executed Output 1:
Enter a decimal value (0 to 15): 11
The hex value is B
Executed Output 2:
Enter a decimal value (0 to 15): 5
The hex value is 5
Executed Output 3:
Enter a decimal value (0 to 15): 31
Invalid input