Novo curso! Todo programador deveria aprender IA generativa!
Experimente uma aula grƔtis+ 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 Respostas
+ 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!š¤š¤