If you enter a hexadecimal character, you want to write a code that distinguishes whether it's hexadecimal or not Use ifelse statements and or
How do I convert hexadecimal to decimal and say no to hexadecimal?
python
Hexadecimal numbers represent characters up to 0-9
and a-f
, so we'll determine if it's hexadecimal.
import re
def is_hex(c):
p = re.compile('[0-9a-fA-F]')
return p.match(c) != None
Wouldn't hex = > decimal conversion do this?
def hex2dec(c):
return int(c, 16)
So if you put it all together, it's this.
import re
def is_hex(c):
p = re.compile('[0-9a-fA-F]')
return p.match(c) != None
def hex2dec(c):
return int(c, 16)
string = input ('Enter a number')
if is_hex(string):
print(' Hexadecimal. {0} in decimal.'format(hex2dec(string)))
else:
print ('Not hexadecimal')
© 2024 OneMinuteCode. All rights reserved.