Python Program

Loop in Python

Loop in Python

In Python, loops are used to iterate over a sequence (like a list, tuple, dictionary, set, or string) or to repeat an action multiple times. Python has two main types of loops: ‘for’ loops and ‘while’ loops.

 

  • for loop

The for loop in Python is used for iterating over a sequence. Here is a basic example:

# Example: Iterating over a list

fruits = [“apple”, “banana”, “cherry”]

for fruit in fruits:

print(fruit)

#Output:

apple

banana

cherry

 

  • While Loop

The while loop in Python is used to repeat a block of code as long as a condition is true. Here is a basic example:

# Example: Printing numbers from 1 to 5

i = 1

while i <= 5:

print(i)

i += 1

#Output:

1

2

3

4

5

 

Loop Control Statements

Python provides several control statements to control the flow of loops:

  • ‘break’: Exits the loop prematurely.
  • ‘continue’: Skips the rest of the code inside the loop for the current iteration and moves to the next iteration.
  • ‘else’: Executes a block of code once when the loop terminates normally (without being interrupted by break).

 

break Example:

# Example: Using break to exit the loop

for i in range(1, 10):

if i == 5:

break

print(i)

#Output

1

2

3

4

 

continue Example:

# Example: Using continue to skip an iteration

for i in range(1, 10):

if i == 5:

continue

print(i)

#Output

1

2

3

4

6

7

8

9

 

else with Loop Example:

# Example: Using else with a loop

for i in range(1, 5):

print(i)

else:

print(“Loop is finished”)

#Output

1

2

3

4

Loop is finished

 

Nested Loops

You can also use loops inside loops (nested loops):

# Example: Nested loop

for i in range(1, 4):

for j in range(1, 4):

print(f’i: {i}, j: {j}’)

#Output

i: 1, j: 1

i: 1, j: 2

i: 1, j: 3

i: 2, j: 1

i: 2, j: 2

i: 2, j: 3

i: 3, j: 1

i: 3, j: 2

i: 3, j: 3

 

Using loops effectively can greatly enhance your ability to process data and perform repetitive tasks in Python programs.

 

 

Take a time to connect our other digital creations such as Instagram , Facebook and Youtube.

Social Media Links of Tech DCode

πŸ‘‰πŸ» YouTube

https://www.youtube.com/channel/UCjJnEdeugftBwQ3yMuD4B_A

πŸ‘‰πŸ»Instagram

https://www.instagram.com/thetechdcode/

πŸ‘‰πŸ»Facebook Page

https://www.facebook.com/thetechdcode

πŸ‘‰πŸ»Telegram Channel

https://t.me/thetechdcode

πŸ‘‰πŸ»Twitter

πŸ‘‰πŸ»Tech DCode Linktree

https://linktr.ee/thetechdcode

πŸ‘‰πŸ»My Personal Handles

https://linktr.ee/virtualshivamin

 

 

 

Leave a Reply

Your email address will not be published. Required fields are marked *