currentnumber = 1 while currentnumber < 10: if currentnumber % 2 == 0: continue…
- User
current_number = 1
while current_number < 10: if current_number % 2 == 0: continue print(current_number) current_number += 1
This is my python program, it's supposed to print out all numbers from 1 - 10 that are odd. It only prints the number 1, why?\
- Assistant
The reason your program only prints the number 1 is because the line
current_number += 1is placed inside theifstatement where you have usedcontinue.The
continuestatement skips the rest of the code inside the loop and goes to the next iteration of the loop. Since you have usedcontinueinside theifcondition for even numbers, the code will skip incrementingcurrent_numberand continue to the next iteration without printing anything.To fix this issue, you need to move the line
current_number += 1outside theifstatement so thatcurrent_numbergets incremented regardless of whether it is even or odd. Here's the corrected code:pythoncurrent_number = 1 while current_number < 10: if current_number % 2 == 0: continue print(current_number) current_number += 1Now the code will print all odd numbers from 1 to 10.
- User
How is it inside the loop? It's not indented.
- Assistant
Apologies for the confusion. You are correct that the line
current_number += 1is not indented inside the loop.The issue with your code is actually on the line
current_number += 1. It is placed after theprint(current_number)statement. This means thatcurrent_numberis getting incremented after it is printed, rather than before.To correct the program, you should move the line
current_number += 1before theprint(current_number)statement. Here's the corrected code:pythoncurrent_number = 1 while current_number < 10: if current_number % 2 == 0: continue current_number += 1 print(current_number)Now, when the program encounters an even number, it will skip to the next iteration without printing anything, and when it encounters an odd number, it will print the number and then increment
current_number.