Click here to Skip to main content
15,881,248 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
2000
4000
5000
4500
3800


If val is greater than 5500, why it is printing smaller values?
and
it gives different outputs after changing the location of print(val) functions.

What I have tried:

salary = [2000,4000, 5000,7000,8000,4500,3800]

for val in salary:
    if val > 5500:
        continue
    print(val)
Posted
Updated 18-Oct-22 8:03am
v2

Simple: if the condition is true, the continue statement is executed, and The rest of the loop body is not executed - the loop immediately goes round for another iteration on the next item in the collection.
 
Share this answer
 
Comments
sunnyjohn 18-Oct-22 13:35pm    
If it's true... then it starts its iteration from the first element(2000) AND stops at the boundary (<5500)??
OriginalGriff 18-Oct-22 14:00pm    
No, read what I said.
If it finds a value that gives a true result, it stops processing that value and moves to teh next.
Your code prints every value that is not greater than 5500. It should be
Python
for val in salary:
    if val > 5500:
        print(val) # print all values greater than 5500
 
Share this answer
 
Comments
sunnyjohn 18-Oct-22 22:06pm    
Thanks so much, Richard!! But, I wanted to understand how the continue statement is functioning.
Richard MacCutchan 19-Oct-22 2:55am    
In your case you do not need a continue statement since it is implied after the end of the if statement. I guess you could change the test in your original code to be
if val <= 5500:
    continue

but that would really be rather pointless. The continue and break statements are there for situations where you need to skip back to the top, or break out of, a somewhat larger loop. See the description at 4. More Control Flow Tools — Python 3.10.8 documentation[^].

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900