- What is looping?
Looping in python: Executing the same statements a Specified number of times is looping or iterative statement.
- Sometimes we require to execute repeatedly then go for the iterative statement.
- Iterative statement executed by different types of loop.
- Types of looping: In python loops available are for loop, while loop.
For loop in python
- For loop is the simplest and easy looping in python.
- In python, we use for each statement.
- For loop in python Syntax
for each_element in sequence:
Do some action or statements
Where sequence can be of any type such as str type, list, set…
- If you know the number of iteration then use for each loop.
- The loop will parse each element in the sequence and while it reaches to end it stops its execution.
- Python for loop flowchart
- Python for loop example
Read character in string one by one using for each Statement
for loop in python
for x in S:
while loop in python
- To execute a set of Statement based on some conditions.
- In python, While loop is used in the situation where you don’t know iteration (number of iterations).
- while loop in python syntax
If the condition is true, then only executes a body of the while.
- Python while loop flowchart
- Python while loop example
while loop in pythonPython123456print("1 to 10 number ")X=1while X<=10:print(X)X+=1print("Program End")
- Infinite loop python: If our condition is not correct the loop may execute continually (keep going on execute) is referred to as an infinite loop.
- Loop will never terminate.
- Infinite loop python Example
while loop in pythonPython12345print("while example")I=0while True:I=I+1print("Program End")
- See above example, whenever while statement evaluated the condition is true so it executed infinite times..
- What is nested loop
Writing one loop inside another is the nested loop.
- Nested loop in python: Yes python allows the nesting of a loop.
- Nested loop example
nested loopPython12345print("netsed example")for I in range(2):for j in range(2):print("I = %i and j = %i" %(I,j))print("Program End")
Loop else python
- What is loop else statement
If loop executed completely without break then else block get executed.
- Loop can be any loop for loop or while loop.
for else pythonPython12345678910print("for else example")C=[10, 20,30]for item in C:if item > 50:print("sorry")breakprint("item processed = ", item)else:print("congrats all item processed")print("Program End")
Else is associated with the break, not with continue.
Else means loop without break.
In case if you don’t write break then else block get executed compulsory.
Else block can be used with if, for while, exception handling block also
Difference between for and while loop
For: Executed body for every item in a given statement
While: executed body as long as the condition is true.