+ 1
[solved] what's wrong with this one line python code?
# find even number in range(1,11) # code must be in one line format if all(x % 2 == 0 for x in range(1,11)) : print(x)
6 Answers
+ 8
Hemant Kosrekar try understanding why that code was used in prime number , although you can use that with even number like =>
for num in range(1,11):
if all(num % 2==0 for i in range(1)) : print(num)
but it doesn't makes any sense . it just checks all(True) or all(False).
It is much better to do it this way though,
for num in range(1, 11) :
if num%2==0: print(num)
+ 4
It's logic is wrong. All returns a Boolean value. True or False.
Here it returns False as not all numbers in the range 1,11 are even.
Therefore it doesn't print anything.
Lemme tell you what you are asking program to do.
Hey python, take all numbers in range (1,11),
divide them all by 2. and if all of them results in 0 remainder value, then print x(the value x holds at the last iteration).
+ 3
this may help:
[print(x) for x in range(1, 11) if x % 2 == 0]
[print(x) for x in range(2, 11, 2)]
for x in range(2, 11, 2): print(x)
+ 2
thanks Abhay ,
i just wanted to do that with one line code
now i understand ,
but in all() function we need to write, for i in range(1,100) ...it doesn't matters but needed
+ 2
thanks John Robotane
your method is too good.
+ 1
# i inspired from this code
for num in range(1,20):
if all(num % i != 0 for i in range(2,num) ) : print(num)
# if it can return all prime number within range so by using all() function ..can we find even number within range
# if it is possible please try with all() function