可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
In the tutorial there is an example for finding prime numbers.
>>> for n in range(2, 10): ... for x in range(2, n): ... if n % x == 0: ... print(n, 'equals', x, '*', n//x) ... break ... else: ... # loop fell through without finding a factor ... print(n, 'is a prime number') ...
I understand that the double == is a test for equality, but I don't understand the "if n % x" part. Like I can verbally walk through each part and say what the statement does for the example. But I don't understand how the percentage sign falls in. What does "if n % x" actually say?
回答1:
Modulus operator; gives the remainder of the left value divided by the right value. Like:
3 % 1
would equal zero (since 3 divides evenly by 1)
3 % 2
would equal 1 (since dividing 3 by 2 results in a remainder of 1).
回答2:
The % does two things, depending on its arguments. In this case, it acts as the modulo operator, meaning when its arguments are numbers, it divides the first by the second and returns the remainder. 34 % 10 == 4
since 34 divided by 10 is three, with a remainder of four.
If the first argument is a string, it formats it using the second argument. This is a bit involved, so I will refer to the documentation, but just as an example:
>>> "foo %d bar"%5 'foo 5 bar'
However, the string formatting behavior is supplemented as of Python 3.1 in favor of the string.format()
mechanism:
The formatting operations described here exhibit a variety of quirks that lead to a number of common errors (such as failing to display tuples and dictionaries correctly). Using the newer str.format()
interface helps avoid these errors, and also provides a generally more powerful, flexible and extensible approach to formatting text.
And thankfully, almost all of the new features are also available from python 2.6 onwards.
回答3:
While this is slightly off-topic, since people will find this by searching for "percentage sign in Python" (as I did), I wanted to note that the % sign is also used to prefix a "magic" function in iPython: https://ipython.org/ipython-doc/3/interactive/tutorial.html#magic-functions
回答4:
In python 2.6 the '%' operator performed a modulus. I don't think they changed it in 3.0.1
The modulo operator tells you the remainder of a division of two numbers.
回答5:
It checks if the modulo of the division. For example, in the case you are iterating over all numbers from 2 to n and checking if n is divisible by any of the numbers in between. Simply put, you are checking if a given number n is prime. (Hint: You could check up to n/2).
回答6:
The modulus operator. The remainder when you divide two number.
For Example:
>>> 5 % 2 = 1 # remainder of 5 divided by 2 is 1 >>> 7 % 3 = 1 # remainer of 7 divided by 3 is 1 >>> 3 % 1 = 0 # because 1 divides evenly into 3