python:我有这个代码(下面),但它反向打印,我该如何反转它

时间:2014-07-18 20:28:05

标签: python decimal reverse

如何反转输出?

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)

1 个答案:

答案 0 :(得分:1)

之前调用递归函数将反转输出:

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 = "")

请注意,我还对该功能进行了一些其他优化。值得注意的是,我删除了不必要的初始化,转换和简化了if-chain,因为已知数字y是0 <= y <= 15的整数。