It's a code that converts hexadecimal to decimal

Asked 2 years ago, Updated 2 years ago, 16 views

I'm working on a program that takes hexadecimal numbers with Python and turns them into decimal numbers


    def hexaToDecimal(hexaString):
        decimalNum = 0
        length = len(hexaString)

        for num in range(0,length):
            x=hexaString[num]
            if 'a'<=x<='f' or 'A'<=x<='F' or '0'<x<='9':
                decimalNum = decimalNum + chToHexa(x) * (16**(length-1)) 
                length = length -1   
    (Optimized)
    def chToHexa(x):
        if x=='A' or 'a':
            return 10
        elif x=='B' or 'b':
            return 11
        elif x=='C' or 'c':
            return 12
        elif x=='D' or 'd':
            return 13
        elif x=='E' or "e":
            return 14
        elif x=='F' or 'f':
            return 15
        else:
            return x
    ```

ChToHexa is a code to correct the hexadecimal number if there is an alphabet 

No matter what number you put in the alphabet, only the value of 10 is returned in chToHexa

I have fixed the code, but I wonder why the number was returned to 100,000

(Unlike the preview, the text below appears in the column with the code written on it.)(T)

python

2022-09-22 08:17

2 Answers

def chToHexa(x):
        if x=='A' or 'a':
            return 10
        elif x=='B' or 'b':
            return 11
        elif x=='C' or 'c':
            return 12
        elif x=='D' or 'd':
            return 13
        elif x=='E' or "e":
            return 14
        elif x=='F' or 'f':
            return 15
        else:
            return x

In if x=='A' or 'a': instead of if x=='A' or 'a': you must give a condition like if x=='A' or 'a':

The or 'a' after is always true.


2022-09-22 08:17

Younghoon explained it well. In addition, you can use x in ('A', 'a') or x.lower()=='a' in the condition of the if statement.


2022-09-22 08:17

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.