+ 1

Guessing the output of code

The question is: What is the output of this code? if 4%2: print(1) else: print(0) The output is 0. However, I'm not sure how the code comes to produce this output. Can someone please explain how this code works? Thank you

11th Mar 2018, 1:05 PM
Joshua Choi
Joshua Choi - avatar
2 ответов
+ 8
A modulus operation evaluates as true in an if statement if there is a remainder after division. Since 4/2 does not have a remainder, it returned false, and executes the else block instead.
11th Mar 2018, 1:14 PM
apex137
apex137 - avatar
+ 2
step by step: 1. the interpreter evaluates '4%2' and gets '0' (zero). 2. the interpreter uses the value of the evaluation in the previous step: 'if 0' and gets False. (in python 0, None, False, have boolean value False) 3. Because the previous step got a False, the else statement will be evaluated: 'print(0)' That's how you get a 0 as output.
11th Mar 2018, 6:04 PM
Ulisses Cruz
Ulisses Cruz - avatar