Learning Python - 4th day (Night - 2)
Watched this tutorial: Click Here
I have learned about Continue, Break and Pass statements.
Let's imagine I have a scenario where I am cycling and I see a bunch of rude people walking through the road after every 10 - 15 seconds. I just have to ignore them.
So while I am cycling
If I see rude people
I will just continue cycling
Also while cycling I often see animals like cat and dogs cross the road.
So while I am cycling
If I see animal crossing road
I will break and stop cycling
In another scenario, if I see a hole in the road, I just have to pass by the hole carefully
So while I am cycling
If I see a hole in the road
I will pass by the hole
Just like previous 3 examples Continue, Break, Pass works to stop or to let the loop run.
Let's have a real example in Python:
Goal is, I want to print all the values from 1 to 20 which are dividable by 3
In normal sentence, I can say like
While the number is less than 20:
if the number modulus by 3 is not 0
then continue
Print the number
What this will do is ignore the while loop whenever the number is undividable by 3
Same happens with break and pass, the difference is Break leaves the loop forever and pass ignores a certain condition
More examples of them:
4.4. break
and continue
Statements, and else
Clauses on Loops
The break
statement, like in C, breaks out of the innermost enclosing for
or while
loop.
Loop statements may have an else
clause; it is executed when the loop terminates through exhaustion of the iterable (with for
) or when the condition becomes false (with while
), but not when the loop is terminated by a break
statement. This is exemplified by the following loop, which searches for prime numbers:
(Yes, this is the correct code. Look closely: the else
clause belongs to the for
loop, not the if
statement.)
When used with a loop, the else
clause has more in common with the else
clause of a try
statement than it does with that of if
statements: a try
statement’s else
clause runs when no exception occurs, and a loop’s else
clause runs when no break
occurs. For more on the try
statement and exceptions, see Handling Exceptions.
The continue
statement, also borrowed from C, continues with the next iteration of the loop:
4.5. pass
Statements
The pass
statement does nothing. It can be used when a statement is required syntactically but the program requires no action. For example:
This is commonly used for creating minimal classes:
Another place pass
can be used is as a place-holder for a function or conditional body when you are working on new code, allowing you to keep thinking at a more abstract level. The pass
is silently ignored:
Comments
Post a Comment