Have you ever felt like you are doing certain tasks again and again in life?
Well, I'm no expert in helping with your life!
Although, if you would ever 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
-
forloop in python repeats over each item of a given sequence (a list or a string), in the order that they appear in the sequence.
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
-
whileloop in python repeats any given set of code until the give condition returns true.
Output:
0
1
1
2
3
5
8
Basic jump statements in python
Jump statements can be used to modify the behaviour of conditional and iterative statements.
break and continue statements fall under the jump statements category.
break statement
- The
breakstatement, borrowed from C programming language, breaks out of the current loop when encountered. - So, any further iterations will not be executed as the
breakstatement changed the flow of the program by coming out of the loop.
Output:
Searching...
Searching...
Searching...
Searching...
Found the treasure
continue statement
- The
continuestatement, borrowed from C programming language, continues with the next iteration of the loop when encountered. - So, any code following the
continuestatement in a loop will be skipped and the loop will continue the next iteration.
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
Else Clauses on Loops
Did you know that loop statements may have an else clause?
Well, it turns out that they can be used!
-
elseclause will be executed when the loop completes through all of the iterations with for loop and when the condition becomes false with while loop.
Output:
Searching...
Searching...
Searching...
Searching...
Searching...
Searching...
Searching...
Searching...
Treasure not found :(
- But
elseclause will not be executed when the loop is terminated by a break statement.
Output:
Searching...
Searching...
Searching...
Searching...
Found the treasure
Latest comments (0)