+ 2

What is wrong with this code please:n = 100 i = 1 while i <= n: if i % 2 == 0: continue print(i) i+=1

I want to print numbers from 1 to 100 excluding those divisible by 2

13th Mar 2022, 1:56 PM
Lean R1
15 Antworten
+ 5
continue cause to skip next statement so it can't reach i+=1 when I=2 and stays there forever , making infinite loop... Add code in description place... edit: NonStop CODING if that is your complete code, then it stil infinite loops.. check again.. correct better way is what Lean R1 found.👍
13th Mar 2022, 2:00 PM
Jayakrishna 🇮🇳
+ 5
Thank you very much guys for the help. I have rewritten the code still using *continue* like this: n = 99 i = 0 while i <= n: i+=1 if i % 2 == 0: continue print(i) And it's running well
13th Mar 2022, 2:10 PM
Lean R1
+ 2
write i+=1 inside if block to increment i when I is divisible by 2. do this to avoid infinite loop or you can do this by without using continue Just write n = 100 i = 1 while i <= n: if i % 2 != 0: print(i) i+=1; # i++ Print for those who are not divisible by 2
13th Mar 2022, 2:07 PM
NonStop CODING
NonStop CODING - avatar
+ 2
Lean R1 it is more appropriate to use a for loop than using while to loop for a fixed number of iterations. Also, if the index skips consistently at a regular interval (e.g., 2 for odd numbers), then code the interval into the range and eliminate the if statement: n = 100 for i in range(1, n+1, 2): print(i)
15th Mar 2022, 5:55 AM
Brian
Brian - avatar
+ 2
wowwww! thanks guys🙏🙏🙏
18th Mar 2022, 2:09 PM
Lean R1
+ 1
Jayakrishna🇮🇳 Fixed😎 thanks for mentioning👍 There was a Indentation mistake😁😁 indentation are really important!
13th Mar 2022, 2:35 PM
NonStop CODING
NonStop CODING - avatar
+ 1
n = 100 i = 1 while i <= n: print(i) i+=2 🙄,You can do that thing without using if/else too...
15th Mar 2022, 2:32 AM
JOKER
JOKER - avatar
+ 1
print(*[i for i in range(1,100,2)], sep="\n") Or this😄😉
15th Mar 2022, 11:06 AM
NEZ
NEZ - avatar
+ 1
print(*range(1,100,2), sep="\n") #or this 😄😉from @Nez's
15th Mar 2022, 11:15 AM
Jayakrishna 🇮🇳
+ 1
NEZ Jayakrishna🇮🇳 Impressive!😍 Nailed it bros! 🔥🔥
15th Mar 2022, 11:24 AM
NonStop CODING
NonStop CODING - avatar
0
Lean R1 Yeah you can do this way as well👍
13th Mar 2022, 2:11 PM
NonStop CODING
NonStop CODING - avatar
0
NonStop CODING thank you 🙏🙏🙏
13th Mar 2022, 2:13 PM
Lean R1
0
NonStop CODING Yes. now..👍 But it about using continue from lesson.. 😇 still fine. no problem.. You're welcome...
13th Mar 2022, 3:02 PM
Jayakrishna 🇮🇳
0
ANONYMOUS 😁😁😁 Excellent Observation!✌️ you insipired me to short down this code further, instead of running the full loop, we can reduce the loop iteration to half, by doing this we can save 50% time 🤓🤓 n=100; i=0; while i < int(n / 2): print( 2 * i + 1 ) i += 1
15th Mar 2022, 4:29 AM
NonStop CODING
NonStop CODING - avatar
0
Brian yeah Great!🤓🤓
15th Mar 2022, 5:59 AM
NonStop CODING
NonStop CODING - avatar