There are 2 types of loops in Python:
- for loop
- while loop
Python for Loop:
The for loop allows you to run a block of code multiple times. A Python for loop is used to iterate over any sequences such as list, tuple, string, etc.
The syntax of the for loop is:
for value in sequence: {loop body}
Flowchart of Python for Loop:
l = [‘java’, ‘Python’, ‘C’, ‘JavaScript’] # access list items using for loop for i in l:
print(i)
java Python C JavaScript
Python for Loop with range():
In Python, a range is a series of values between two numeric intervals. We can use the built-in function range() that takes an integer argument and returns an ordered list of numbers between two inclusive boundaries.
values = range(5)
Here, 5 inside range() defines a range containing values 0, 1, 2, 3, 4.
# use of range() to define a range of values for i in values:
values = range(5)
print(i)
1 2 3 4 5
Python for loop with else:
A for loop can have an optional else block as well. The else part is executed when the loop is finished.
no = [1, 2, 3] for i in no:
print(i)
else:
print(“No items left.”)
1 2 3 No items left
Python while Loop:
The Python while loop is an example of the general type of loop, where the code is run once until a certain condition becomes true.
while expression: statement(s)
Flowchart for Python While Loop:
# initialize the variable # while loop from i = 1 to 5
i = 1
n = 5
while i <= n:
print(i)
i = i + 1
1 2 3 4 5
Python Infinite while Loop:
The loop will run as long as the condition is True. Thus, the loop runs for an undefined amount of time.
# infinite while loop
while True:
# body of the loop
Python While loop with else:
A while loop with an else block is similar to the if then else. While you might think the loop will always end once it has executed its body, a single line of code in the else block can cause execution to exit early.
count= 0 while count < 5:
print(‘Inside while loop’)
count = count + 1
else:
print(‘Inside else’)
Inside while loop Inside while loop Inside while loop Inside while loop Inside while loop Inside else
I’m truly enjoying the design and layout of your blog. It’s a very easy on the
eyes which makes it much more pleasant for me to come here and visit more often. Did you hire out a developer to create your theme?
Great work!