Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
11 views

looping statements in python

Uploaded by

itnvsjnv
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views

looping statements in python

Uploaded by

itnvsjnv
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 3

LOOPING STATEMENT IN PYTHON

Looping statements in Python are used to execute a block of code repeatedly as long as
a specified condition is met or for a predefined number of iterations.

two main types of loops in python:

for and while.

Additionally, the break, continue, and pass statements are often used to control the flow within
these loops.

1. for Loop

A for loop iterates over a sequence (like a list, tuple, string, or range) and executes the block of
code for each element.

Example:

fruits = ["apple", "banana", "cherry"]


for fruit in fruits:
print(fruit)

output:
apple
banana
cherry
example range:

for i in range(5): # Iterates from 0 to 4


print(i)
output:
0
1
2
3
4

2. while Loop

A while loop executes as long as a specified condition is True.

count = 0
while count < 5:
print("Count is:", count)
count += 1
output:

Count is: 0
Count is: 1
Count is: 2
Count is: 3
Count is: 4
Infinite loop (use with caution)
while True:
print("This will run forever unless stopped.")
break # Avoids infinite loop

3. Controlling Loop Execution

a. break Statement

Used to exit the loop prematurely.

for i in range(10):
if i == 5:
break
print(i)

output:

0
1
2
3
4

b. continue Statement

Skips the current iteration and moves to the next.

for i in range(5):
if i == 2:
continue
print(i)

output:
0
1
3
4
c. pass Statement

Used as a placeholder when no action is required.

for i in range(5):
if i == 3:
pass # Do nothing
else:
print(i)

output:
0
1
2
4

Nested Loops

Loops inside loops for complex iterations.

Example: Multiplication table


for i in range(1, 4):
for j in range(1, 4):
print(f"{i} x {j} = {i * j}")

output:
1x1=1
1x2=2
1x3=3
2x1=2
2x2=4
2x3=6
3x1=3
3x2=6
3x3=9

You might also like