+ 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 Answers
+ 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!๐ค๐ค