user3854446
user3854446

Reputation: 59

python: I have this code (below) but it prints in reverse, how can I reverse it

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)

Upvotes: 0

Views: 86

Answers (1)

David Zwicker
David Zwicker

Reputation: 24268

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.

Upvotes: 1

Related Questions