Ever felt like you are doing certain tasks again and again in your life?
Well, I'm no expert in helping with your life! However, if you face the same situation in a programming language, I can help you with that.
In programming, we can repeat certain tasks using loops. Let's go through them one by one.
for loop in python repeats over each item of a given sequence (a list or a string), in the order that they appear in the sequence.
Example:
Output:
I want to watch a movie directed by James Cameron
I want to watch a movie directed by Christopher Nolan
I want to watch a movie directed by Steven Spielberg
But, let's say you are a programmer who needs to iterate over a sequence of numbers, given the limit you want. Well, then you can make use of the built-in function range() which generates arithmetic progressions:
Output:
0
1
2
3
4
while loop in python repeats any given set of code until the give condition returns true.
Example:
Output:
0
1
1
2
3
5
8
Jump statements can be used to modify the behaviour of conditional and iterative statements.
break and continue statements fall under the jump statements category.
The break statement, borrowed from C programming language, breaks out of the current loop when encountered. So, any further iterations will not be executed as the break statement changed the flow of the program by coming out of the loop.
Example:
Output:
Searching...
Searching...
Searching...
Searching...
Found the treasure
The continue statement, borrowed from C programming language, continues with the next iteration of the loop when encountered.
So, any code following the continue statement in a loop will be skipped and the loop will continue the next iteration.
Example:
Output:
Found an even number 2
Found an odd number 3
Found an even number 4
Found an odd number 5
Found an even number 6
Found an odd number 7
Found an even number 8
Found an odd number 9
The pass statement does nothing.
Wow, that’s a bummer!
Hmmm…
Then, why do we need it?
Well, it can be used when a statement is required syntactically but the program requires no action.
Let’s see an example:
This is also commonly used for creating empty classes so that we can come back later and code something:
Did you know that loop statements may have an else clause?
Well, it turns out that they can be used!
else clause will be executed when the loop completes through all of the iterations with for loop and when the condition becomes false with while loop.
Example:
Output:
Searching...
Searching...
Searching...
Searching...
Searching...
Searching...
Searching...
Searching...
Treasure not found :(
But else clause will not be executed when the loop is terminated by a break statement.
Example:
Output:
Searching...
Searching...
Searching...
Searching...
Found the treasure
Code along and have fun.