ELIM5 : I'm dumb | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

ELIM5 : I'm dumb

take a look at the code: x = 20 for num in range(x): if num % 2: print(f"It is even. ({num+1})") else: print(f"It is odd. ({num+1})") it would output: It is odd. (1) It is even. (2) It is odd. (3) It is even. (4) It is odd. (5) It is even. (6) It is odd. (7) It is even. (8) It is odd. (9) It is even. (10) It is odd. (11) It is even. (12) It is odd. (13) It is even. (14) It is odd. (15) It is even. (16) It is odd. (17) It is even. (18) It is odd. (19) It is even. (20) but why the trick {num+1} adding 1 each to get the correct number? because of the range() function? Is {num+1} adding +1 to range() ?

18th Oct 2021, 9:39 PM
Naung Mon Oo
Naung Mon Oo - avatar
1 Answer
+ 1
num % 2 gives the remainder of dividing num by 2. When a number is even this is 0, when a number is odd it is 1. Python implicitly interprets 1 as True and 0 as False in contexts where a boolean is required such as an if condition. So num % 2 will evaluate to True for odd numbers and False for even numbers. That means the if condition is fulfilled by odd numbers. But since you want even numbers you have to add 1. You can get rid of the requirement to add 1 if you replace if num % 2: with if num % 2 == 0:
18th Oct 2021, 10:19 PM
Simon Sauter
Simon Sauter - avatar