简体   繁体   English

无法理解 python 代码的功能

[英]Unable to understand the functioning of the python code

def dtb(num):
    if num > 1:
        dtb(num//2)
    print(num%2,end='')

dtb(10)

I understand the recursion part but not able to understand the rest code.Can someone please provide a step by step explanation.我理解递归部分,但无法理解 rest 代码。有人可以提供一步一步的解释。 Thanks in advance.提前致谢。

This function converts an integer decimal number to a binary number.此 function 将 integer 十进制数转换为二进制数。

// - operator of floor division. // - 楼层划分运算符。 For example (13//5) will return 2例如 (13//5) 将返回 2

PS. PS。 You need to write dtb(10) instead of def(10) to call tour method.您需要编写 dtb(10) 而不是 def(10) 来调用 tour 方法。

If it's the print part thats confusing you, it will print num mod 2 (the remainder after dividing by 2).如果是打印部分让您感到困惑,它将打印 num mod 2 (除以 2 后的余数)。 The end='' is so python doesn't print a new line after, which it does by default. end='' 如此 python 之后不会打印新行,默认情况下会打印。

As for the def(10), I'm assuming thats a typo.至于 def(10),我假设那是一个错字。 It should be dtb(10) which would call the recursive function on the integer 10.它应该是 dtb(10),它将调用 integer 10 上的递归 function。

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

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