Reputation: 57
I'm trying to make a hexadecimal to decimal calculator and i'm trying to check if the input has integer or character.
How can I accomplish this?
def hex2dec(value):
dict = {'A':10,'B':11,'C':12,'D':13,'E':14,'F':15}
strVal = str(value)
length = len(strVal)
decimal = 0
for i in range(0,length):
try:
int(strval[i:i+1])
val = "int"
except ValueError:
val = "not int"
return val
value = int(input("Enter Hexadecimal Value: "),16)
print("Value in Hexadecimal : ", hex2dec(value))
Whenever I run the codes and input any single digit or alphabet from A to F it returns int
.
Anyone knows the solution to this?
Upvotes: 0
Views: 41
Reputation: 22457
You always get "int"
because the function is always called with an int
. The variable value
gets converted to an integer because of int(..)
in the input
line.
If you want to check first, feed the original string input into your function:
value = input("Enter Hexadecimal Value: ")
You don't need to check one character at a time, this will work as well:
try:
int(strVal)
val = "int"
except ValueError:
val = "not int"
Note that there is no good reason to check in your function! Even if you seemingly enter an integer -- 123
--, you must still process this as a hexadecimal number. Checking if it's also an integer has no use at that point.
Upvotes: 0
Reputation: 798
Extending the previous answer, you could do:
if (strval[i:i+1] in dict.keys()) or (type(strval[i:i+1]) == int):
val = 'int'
else
'val = 'not int'
in order to check if the value is an int
or in your dict (additionally you get some extensibility..)
Upvotes: 0
Reputation: 19367
With this line
value = int(input("Enter Hexadecimal Value: "),16)
you have already converted the provided value to an integer.
If you want to perform the conversion yourself, first accept what they have entered as a string (remove the use of int()
in the above statement).
Also note that a submission of "12"
is a valid hexadecimal value, with a decimal value of 18
.
Upvotes: 1