0

How can I reverse the output?

def dectohex(num):
        z = int(0)
        y = int(0)
        if num > 0:
            z = num // 16
            y = int((num % 16))
            if y == 10:
                print("A", end = "")
            elif y == 11:
                print("B", end = "")
            elif y == 12:
                print("C", end = "")
            elif y == 13:
                print("D", end = "")
            elif y == 14:
                print("E", end = "")
            elif y == 15:
                print("F", end = "")           
            elif y == 0 or 1 or 2 or 3 or 4 or 5 or 6 or 7 or 8 or 9:
                print(y, end = "")
            dectohex(z)

inp = int(input("Enter number "))
dectohex(inp)
Jason B
  • 7,097
  • 8
  • 38
  • 49
  • try moving your recursive call to after you calculate z – Ben Jul 18 '14 at 20:31
  • you made a mistake. What you meant indeed is : `elif y == 0 or y == 1 or y == 2 or y == 3 or y == 4 or y == 5 or y == 6 or y == 7 or y == 8 or y == 9:` which could also be re-written nicely using the `in` keyword `elif y in [0,1,2,3,4,5,6,7,8,9]:` – Stephane Rolland Jul 18 '14 at 20:31
  • http://stackoverflow.com/questions/14678132/python-hexadecimal check this out, more pythonic way to convert decimals to hex values : ) – Lukas Kozlowski Jul 18 '14 at 20:55

1 Answers1

1

Calling the recursive function earlier will reverse the output:

def dectohex(num):
    if num > 0:
        z = num // 16
        dectohex(z)
        y = num % 16
        if y == 10:
            print("A", end = "")
        elif y == 11:
            print("B", end = "")
        elif y == 12:
            print("C", end = "")
        elif y == 13:
            print("D", end = "")
        elif y == 14:
            print("E", end = "")
        elif y == 15:
            print("F", end = "")           
        else:
            print(y, end = "")

Note that I also made some other optimization to the function. Notably, I removed unnecessary initialization, casting and simplified the if-chain, since the number y is known to be an integer with 0 <= y <= 15.

David Zwicker
  • 23,581
  • 6
  • 62
  • 77