简体   繁体   English

python:我有下面的代码,但是它反向打印,我该如何反转

[英]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)

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. 值得注意的是,我删除了不必要的初始化,转换并简化了if链,因为已知数字y是0 <= y <= 15的整数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM