+ 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
15 Réponses
+ 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.👍
+ 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
+ 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
+ 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)
+ 2
wowwww! thanks guys🙏🙏🙏
+ 1
Jayakrishna🇮🇳
Fixed😎
thanks for mentioning👍
There was a Indentation mistake😁😁
indentation are really important!
+ 1
n = 100
i = 1
while i <= n:
print(i)
i+=2
🙄,You can do that thing without using if/else too...
+ 1
print(*[i for i in range(1,100,2)], sep="\n")
Or this😄😉
+ 1
print(*range(1,100,2), sep="\n")
#or this 😄😉from @Nez's
+ 1
NEZ
Jayakrishna🇮🇳
Impressive!😍
Nailed it bros! 🔥🔥
0
Lean R1
Yeah you can do this way as well👍
0
NonStop CODING thank you 🙏🙏🙏
0
NonStop CODING
Yes. now..👍
But it about using continue from lesson.. 😇
still fine. no problem.. You're welcome...
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
0
Brian
yeah Great!🤓🤓