Please can anyone explain the output? I don't understand i try but still no. Why numbers are evens !? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

Please can anyone explain the output? I don't understand i try but still no. Why numbers are evens !?

def numbers(x): for i in range(x): if i % 2 == 0: yield i print(list(numbers(11))) # output --> [0,2,4,6,8]

27th Oct 2021, 2:10 PM
ola Scar
ola Scar - avatar
4 Answers
+ 3
% operator return remainder... Therefore, it will print [0,2,4,6,8,10] (range always work one less) as per your if logic ~ 0%2 == 0 true -> 0 1%2 == 0 false 2%2 == 0 true -> 2 3%2 == 0 false 4%2 == 0 true -> 4 5%2 == 0 false 6%2 == 0 true -> 6 7%2 == 0 false 8%2 == 0 true -> 8 9%2 == 0 false 10%2 == 0 true -> 10
27th Oct 2021, 2:27 PM
I Am a Baked Potato
I Am a Baked Potato - avatar
+ 2
% is the modulo operator. It divides two numbers and returns the reminder For example: There are 4 people who wants to eat a pizza. The pizza is cutted in 9 exactly portions. All of them must eat the same quantity of pizza so you give them 2 portions each. 1 portion is the reminder So in numbers it will be: 9%4 = 1 a % b The operation is like: a - floor(a/b) * b Where floor(a / b) represents the number of times you can divide a by b. floor(a / b) * b is the amount that was successfully shared entirely The total ‘a’ minus what was shared equals the reminder of the division So using your code as example the reminder of any number % 2 can be 0 or 1 If the number es even : 2,4,6,8 The operation will return 0 2%2 = 0 4%2=0 Because there are no reminders!! You can divide it entirely If the number is odd: 1,3,5,7 The operation will return 1 1%2 = 1 3%2 = 1 5%2 = 1
27th Oct 2021, 2:29 PM
Guillem Padilla
Guillem Padilla - avatar
+ 2
5 / 2 = 2.5 5 // 2 = 2 5 % 2 = 1 <--- 2 can only go into 5 evenly twice and 1 (remainder) is left over (5-2-2 = 1)
27th Oct 2021, 2:34 PM
Paul K Sadler
Paul K Sadler - avatar
+ 2
Thanks a lot community ! Sweet pizza 😋
28th Oct 2021, 11:06 PM
ola Scar
ola Scar - avatar