简体   繁体   English

需要说明功能如何反向打印数字

[英]Need explanation of how function works printing digits in reverse

I cheated after giving up of how to figure out how to print digits backwards making a function for it but I still do not quite understand how it works. 我放弃了如何弄清楚如何向后打印数字的功能,但为此作弊,但我仍然不太了解它是如何工作的。 For instance why does it print the digits backwards and not in order? 例如,为什么它向后打印数字而不是按顺序打印?

def print_digits(n):
    """
      >>> print_digits(13789)
      9 8 7 3 1
      >>> print_digits(39874613)
      3 1 6 4 7 8 9 3 
      >>> print_digits(213141)
      1 4 1 3 1 2 
    """
    while n > 0:
        print n % 10
        n = n / 10 

I would appreciate a line by line explanation starting with the while loop. 我希望从while循环开始逐行进行解释。 I've tried tracing it in my head and on paper but just can't grasp the code in the function. 我已经尝试过在我的头上和纸上追踪它,但是无法掌握函数中的代码。

In the first line in the loop the '%' operator devides the number given by 10 and returns the rest only, means the fraction of the division (25 : 10 = 2.5, so it returns the 5 only!). 在循环的第一行中, '%'运算符将10给出的数字除以,然后仅返回其余数,表示除法的分数(25:10 = 2.5,因此仅返回5!)。

The line 'n/10' then does exactly the other way around and stores part left of the comma into the variable itself, as the '/' operator returns only the left part of the comma. 然后,行“ n / 10”正好相反,并将逗号的剩余部分存储到变量本身中,因为“ /”运算符仅返回逗号的左边部分。

In short you can say: 简而言之,您可以说:

  1. n%10 returns only the rest of the divison n%10仅返回其余的除法
  2. n/10 "throws" the rest of the division away n / 10 “扔”除法师的其余部分
  3. the code repeats 代码重复

% operator returns the remainder of division. %运算符返回除法的余数。 (20%3=2,24%5=4). (20%3 = 2,24%5 = 4)。 When you divide a number by 10 remainder is always the last digit. 当您将数字除以10时,余数始终是最后一位。 For example 123/10=12 & remainder is 3. So 123%10=3. 例如123/10 = 12,余数为3。因此123%10 = 3。 Inside the while loop while n is greater than 0 the last digit of n is printed. 在while循环内,当n大于0时,将打印n的最后一位。

And because of the line n=n/10, n becomes n/10. 并且由于线n = n / 10,所以n变为n / 10。 Here integer division has used so finally value of n will become 0 and then the loop will stop.( if n is initially 123 value of n will change as 123,12,1,0 and then loop will stop.) 这里使用了整数除法,因此最终n的值将变为0,然后循环将停止(如果n最初是123,则n的值将变为123,12,1,0,然后循环将停止。)

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

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