regularpython@gmail.com
Python Loops
Python loops are used to iterate the sequential data. Python loops are,
Ø For loop
Ø While loop
Ø Nested loop
For Loop:
For loop is used to execute sequential data. It loops based on length of the sequential data.
Example1: This example shows how to iterate string value.
name = 'python'
for k in name:
print(k)
output:
p
y
t
h
o
n
Example2: How to print List data.
fruits = ['Apple', 'Mangos', 'Banana', 'Oranges', 'Grapes']
for fruit in fruits:
print(fruit)
output:
Apple
Mangos
Banana
Oranges
Grapes
Example3: How to print tuple data.
fruits = ('Apple', 'Mangos', 'Banana', 'Oranges', 'Grapes')
for fruit in fruits:
print(fruit)
output:
Apple
Mangos
Banana
Oranges
Grapes
Example4: How to print dictionary data.
student = {"name": 'sai', 'nuber':1, 'marks':90, 'subjects': ['science', 'maths', 'physics']}
for item in student.items():
print(item)
output:
('name', 'sai')
('nuber', 1)
('marks', 90)
('subjects', ['science', 'maths', 'physics'])
While Loop:
While loop is mainly used to continuous iteration. This is a very danger loop, you should handle this otherwise program will not stop. It iterates continuously.
Eample1: Without handling the loop
while True:
print('hello')
output:
hello
hello
hello
hello
hello …
Example2: with handling the loop.
count = 1
while True:
print('hello')
if count == 5:
break
count+=1
output:
hello
hello
hello
hello
hello
Nested Loops:
groups = [['apple', 'banana'], ['tomato', 'onion'], ['bat', 'ball']]
for group in groups:
for item in group:
print(item)
output:
apple
banana
tomato
onion
bat
ball