Reputation: 1
Let's say the user enters the integer 10. I know the print(the_sum) line produces 12 because 3 and 9 are both chosen. I don't understand why it is 3 and 9 that are chosen. In the if statement line: "number % 2 and not number % 3" is where I am getting confused. I guess I just don't understand what the "and not" is doing to change that line to produce 3 and 9 to be added for the_sum. Any help would be greatly appreciated so I can move forward with more understanding.
the_max = int(input("Enter the upper limit:"))
the_sum = 0
extra = 0
for number in range(1,the_max):
if number%2 and not number%3:
the_sum = the_sum + number
else:
extra += 1
print(the_sum)
print(extra)
Upvotes: 0
Views: 141
Reputation: 129537
if number%2 and not number%3:
To understand this line you first have to understand how ints are treated when used in a bool context. In a nutshell, any int that has a value of 0
is considered False
and all other ints are considered True
.
Now, when is n % 2
equal to 0
so as to be considered False
? Well, when n
is evenly divisible by 2. The same can be said for n % 3
: it's False
when n
is evenly divisible by 3. So that if-statement can be thought of as:
If ((number is not divisible by 2) and (number is divisible by 3))
Note that since n % 3
is true for all ints not divisible by 3, not n % 3
is true for all ints that are divisible by 3.
This matches the output you see: 9
and 3
are the only two integers in the range 1 to 9 (inclusive) that satisfy this condition.
Upvotes: 3
Reputation: 1123360
Try out the components for 9:
>>> 9 % 2
1
>>> 9 % 3
0
>>> not 9 % 3
True
>>> 9 % 2 and not 9 % 3
True
Numeric 0 is false in a boolean context, and any other number is considered true. not 0
is therefor true.
For any other number, the combination never returns true values for both tests:
>>> 1 % 2
1
>>> 1 % 3
1
>>> not 1 % 3
False
In other words, only numbers that are not divisible by 2 but are divisible by 3 are picked.
To simplify understanding, you could explicitly test for numeric 0 instead:
if number % 2 != 0 and number % 3 == 0:
Upvotes: 1
Reputation: 9913
The modulo operator (%
) will return an int, which corresponds to the remainder of division of the 2 numbers. In if
statements, Python treats numbers according to their truthiness -- 0
is falsey, everything else is truthy. So this code is being a little bit too clever. I would clarify it like so:
if number % 2 != 0 and number % 3 == 0:
Upvotes: 0