Python Code Questions

Asked 2 years ago, Updated 2 years ago, 14 views

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

2022-09-21 21:25

1 Answers

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')


2022-09-21 21:25

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.