When you want some statements to execute a hundred times, you don’t repeat them 100 times.
Think of when you want to print numbers 1 to 99. Or that you want to say Hello to 99 friends.
In such a case, you can use loops in python.
Here, we will discuss 4 types of Python Loop:
Python For Loop
Python While Loop
1. For Loop
Python for loop can iterate over a sequence of items. The structure of a for loop in Python is different than that in C++ or Java.
That is, for(int i=0;i<n;i++) won’t work here. In Python, we use the ‘in’ keyword.
Lets see a Python for loop Example:
Nested for Loops in Python
You can also nest a loop inside another. You can put a for loop inside a while, or a while inside a for, or a for inside a for, or a while inside a while.
Or you can put a loop inside a loop inside a loop. You can go as far as you want.
2. Python While Loop
A while loop in python iterates till its condition becomes False. In other words, it executes the statements under itself while the condition it takes is True.
When the program control reaches the while loop, the condition is checked. If the condition is true, the block of code under it is executed.
Remember to indent all statements under the loop equally. After that, the condition is checked again.
This continues until the condition becomes false.
Then, the first statement, if any, after the loop is executed.
Like an if statement, if we have only one statement in while’s body, we can write it all in one line.
while a>0: print(a); a-=1
No comments:
Post a Comment