SHARE
SPREAD
HELP

The Tradition of Sharing

Help your friends and juniors by posting answers to the questions that you know. Also post questions that are not available.


To start with, Sr2Jr’s first step is to reduce the expenses related to education. To achieve this goal Sr2Jr organized the textbook’s question and answers. Sr2Jr is community based and need your support to fill the question and answers. The question and answers posted will be available free of cost to all.

 

#
Authors:
Y Daniel Lang
Chapter:
.selections
Exercise:
Programming Excercises
Question:33 | ISBN:978013274719 | Edition: 6

Question

(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

TextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbook

Answer

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

 

0 0

Discussions

Post the discussion to improve the above solution.