+ 4

Why is this code not working?

I want to print all the even numbers between 0 to 10 using while loop. But the code is not printing anything. This is the code, please help. x = 0 while x<= 10: if x%2 == 0: print(x) x += 1

19th Oct 2020, 2:47 PM
Aditya
Aditya - avatar
6 ответов
0
x=0 while x<=10: print(x) x+=2 This is actually you wanted to do
19th Oct 2020, 5:18 PM
Rowdy Reddy
Rowdy Reddy - avatar
+ 7
You should change your code: x = 0 while x<= 10: if (x%2==0): print(x) x += 1 The x variable should be incremented always, not only if x%2==0, so you should move x+=1 out of the if statement.
19th Oct 2020, 2:57 PM
Artem 🇺🇦
Artem 🇺🇦 - avatar
+ 7
Hi Aditya, This code is not working because of incorrect indentation, that is, x += 1 should not be indented for if statement. Only print(x) should be indented. The correct code, x = 0 while x <= 10: if x%2 == 0: print(x) x += 1
19th Oct 2020, 2:58 PM
Rahul Hemdev
Rahul Hemdev - avatar
+ 5
Thanks everyone 😃
19th Oct 2020, 3:24 PM
Aditya
Aditya - avatar
+ 3
#identation problem, #You wrote x += 1 in if, after x=1 it won't execute ever so infinite looping, take it out of if. Corrected code x = 0 while x<= 10: if x%2 == 0: print(x) x += 1
19th Oct 2020, 2:57 PM
Jayakrishna 🇮🇳
+ 3
This is because you are incrementing value of "x" only when the if condition is true otherwise it is not incrementing thus leading to an infinite loop. one solution is to correct the indent as Instructed by others or change the incremental value to satisfy the condition (like this)👇 https://code.sololearn.com/cpMN1QFmW0Yf/?ref=app
19th Oct 2020, 2:58 PM
Arsenic
Arsenic - avatar