Write a code that distinguishes hexadecimal characters by entering one hexadecimal character.
1) Use if-else statements 2) Utilize and/p
Execution result:
ex) Enter hexadecimal Korean characters: 8
Decimal ====> 8
Enter hexadecimal Korean characters: F
Decimal ====> 15
How do I write the code...
python
You posted a similar question last time , but this time we will answer it without using a standard library as much as possible.
First of all, you can do this for hexadecimal discrimination.
def is_hex(c):
is_numeric = ord('0') <= ord(c) <= ord('9')
is_lowercase = ord('a') <= ord(c) <= ord('f')
is_uppercase = ord('A') <= ord(c) <= ord('F')
return is_numeric or is_lowercase or is_uppercase
Then, you can change it to decimal like this is how you do it.
def hex_to_dec(c):
is_numeric = ord('0') <= ord(c) <= ord('9')
is_lowercase = ord('a') <= ord(c) <= ord('f')
is_uppercase = ord('A') <= ord(c) <= ord('F')
if is_numeric:
return ord(c) - ord('0')
elif is_lowercase or is_uppercase:
return ord(c.lower()) - ord('a') + 10
If you want to put them all together, you can do this.
def is_hex(c):
is_numeric = ord('0') <= ord(c) <= ord('9')
is_lowercase = ord('a') <= ord(c) <= ord('f')
is_uppercase = ord('A') <= ord(c) <= ord('F')
return is_numeric or is_lowercase or is_uppercase
def hex_to_dec(c):
is_numeric = ord('0') <= ord(c) <= ord('9')
is_lowercase = ord('a') <= ord(c) <= ord('f')
is_uppercase = ord('A') <= ord(c) <= ord('F')
if is_numeric:
return ord(c) - ord('0')
elif is_lowercase or is_uppercase:
return ord(c.lower()) - ord('a') + 10
string = input ('Enter a number')
if is_hex(string):
print(' Hexadecimal. {0} in decimal.'format(hex_to_dec(string)))
else:
print ('Not hexadecimal')
© 2025 OneMinuteCode. All rights reserved.