Introduction:
In this Python code, we will learn how to use a for loop to print values from 0 to 6, excluding the number 3. We will explain the logic behind the code and show the output.
Code:
#Prints values from 0 to 6 except 3
num = 0
for num in range(6):
num = num + 1
if num == 3:
continue
print('Num has value ' + str(num))
print('End of loop')
Logic:
- We start by initializing the variable “num” to 0.
- Using a for loop, we iterate through the range of numbers from 0 to 5 (range(6)).
- Inside the loop, we increment the value of “num” by 1 using the expression “num = num + 1”.
- We then use an if statement to check if “num” is equal to 3.
- If “num” is equal to 3, the continue statement is executed, which skips the remaining lines of code in the loop and moves on to the next iteration of the loop.
- If “num” is not equal to 3, the print statement is executed, which displays the value of “num” with the string ‘Num has value ‘.
- After the loop ends, the print statement ‘End of loop’ is executed.
Output:
>> Num has value 1
>> Num has value 2
>> Num has value 4
>> Num has value 5
>> Num has value 6
>> End of loop