Could somebody explain why does the last num is printed incorrectly? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 2

Could somebody explain why does the last num is printed incorrectly?

for i in range(1,10): if i%2==0: print(i,"is odd") else: print(i,"is even") print(i) #result 1 is odd 2 is even 3 is odd 4 is even 5 is odd 6 is even 7 is odd 8 is even 9 is odd 9

15th May 2019, 6:10 AM
ENDERllama 15
ENDERllama 15 - avatar
3 Answers
+ 2
Yes, get rid of the last line. By the way, the code gives the wrong answers. If the remainder is 0 after dividing i by 2, i is even, not odd. It should be if i % 2 != 0: not if i % 2 == 0: You can also just say if i % 2: because that's the same as saying if i % 2 !=0: Here's a short way of saying it for i in range(1, 10): print(i, "is odd" if i % 2 else "is even") You can even write the whole thing in one line, which is fun to do, but not good readable coding style 😅 print(*(f'{i} is {"odd" if i % 2 else "even"}' for i in range(1, 10)), sep="\n")
15th May 2019, 10:20 AM
David Ashton
David Ashton - avatar
+ 1
Ok thanks
15th May 2019, 6:18 AM
ENDERllama 15
ENDERllama 15 - avatar
0
What is "(f'....",i mean the "f"?
15th May 2019, 10:47 AM
ENDERllama 15
ENDERllama 15 - avatar