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:34 | ISBN:978013274719 | Edition: 6

Question

(Hex to decimal) Write a program that prompts the user to enter a hex character and displays its corresponding decimal integer. Here are some sample runs:


Enter a hex character: A
The decimal value is 10

Enter a hex character: a
The decimal value is 10

Enter a hex character: 5
The decimal value is 5


Enter a hex character: G
Invalid input
 

TextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbook

Answer

Promgram Code:

#Function to convert a hex character to its decimal integer value.
def hexToDecimal(hexChar):
    decimal = 0

    if hexChar.isdigit():
        # Convert the hex digit to decimal if it is a digit
        decimal = int(hexChar)  
    else:
        # Convert the hex character to uppercase
        hexChar = hexChar.upper()  

        if hexChar == 'A':
            decimal = 10
        elif hexChar == 'B':
            decimal = 11
        elif hexChar == 'C':
            decimal = 12
        elif hexChar == 'D':
            decimal = 13
        elif hexChar == 'E':
            decimal = 14
        elif hexChar == 'F':
            decimal = 15

    return decimal


# Prompt the user to enter a hex character
hexChar = input("Enter a hex character: ")

# Convert the hex character to decimal
decimal_value = hexToDecimal(hexChar)

# Display the result
print("The decimal value is", decimal_value)

Executed Output 1:

Enter a hex character: A
The decimal value is 10

 

0 0

Discussions

Post the discussion to improve the above solution.