Can you please explain the output of this code? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 5

Can you please explain the output of this code?

def chek(x): if x%3==0: return False; return True; a = sum([i for in range(6) if chek(i)]); print(a)

4th Mar 2020, 9:02 AM
APC (Inactive for a while)
APC (Inactive for a while) - avatar
7 Answers
+ 5
The chek() function checks if the given number is not divisible by 3 (returns False if x is divisible by 3 and True otherwise). [i for i in range(6) if chek(i)] creates list from numbers 0, 1, 2, 3, 4, 5 (range(6)) filtering them through function chek() (numbers that are not divisible by 3). The list will be [1, 2, 4, 5] sum returns the sum of that numbers 1+2+4+5 = 12 print outputs the result. Bur your code will not compile because you forgot to put i between "for" and "in" line a = sum([i for in range(6) if chek(i)]); should be: a = sum([i for i in range(6) if chek(i)]);
4th Mar 2020, 9:32 AM
andriy kan
andriy kan - avatar
+ 5
4th Mar 2020, 9:35 AM
¯\_(ツ)_/¯
¯\_(ツ)_/¯ - avatar
+ 4
WhyFry Yes but can you explain?
4th Mar 2020, 9:25 AM
APC (Inactive for a while)
APC (Inactive for a while) - avatar
+ 4
The Sylar yes but what that return True and False doing there with different indentation?
4th Mar 2020, 9:29 AM
APC (Inactive for a while)
APC (Inactive for a while) - avatar
+ 3
def chek(x): if x%3==0: return False; return True; b = sum([i for i in range(6) if chek(i)]) print(b) About the above code in short if the number in the range(6) have a zero remainder on dividing with 3 (Basically a multiple of 3) then it is not added in the list because the function chek(i) will return False for that. So the list will be b = [1, 2, 4, 5] b = sum([1, 2, 4, 5]) gives 12 Basic maths... Just add all elements
4th Mar 2020, 9:34 AM
Utkarsh Sharma
Utkarsh Sharma - avatar
+ 2
Search 'list comprehension'. Basically, from range 0 to 5, it check which number is not divisible by 3. So they will be 1,2,4,5. And sum of them is 12. That is ! :)
4th Mar 2020, 9:26 AM
The Sylar
+ 2
chek(0) will get false, right? So a will become: a = [i for i in range(6) if false] So, 0 will not be inserted because 'if' statement is false. So do the 3. But 1,2,4,5 will be included in the list because 'if' statement become true from chek(1 or 2 or 4 or 5). Hope it's clear now.
4th Mar 2020, 9:43 AM
The Sylar