Loops

  • A loop statement allows us to execute a statement or group of statements multiple times.
  • A loop is used to iterate over the python objects and perform any logic with the data

Types

  • While Loop
  • For Loop
  • Nested Loop

While Loop

  • while loop can execute a set of statements as long as a condition is true.
  • It is used in the scenario where we don’t know the number of iterations in advance.
while expression:

   statement(s)

While with else

Else statement we can run a block of code once when the condition no longer is true

while expression:

   statement(s)

else:

  statements(s)

For Loop

A for loop is used for iterating over a sequence or iterable objectlike list , tuple etc

Syntax

for iterating_var in sequence:

  statements(s)
Y=7

for x in range(7):
  print(x)

Else in For Loop

Else keyword in a for loop specifies a block of code to be executed when the loop is finished.

for iterating_var in sequence:

  statements(s)

else:

   statements(s)

Nested Loops

The “inner loop” will be executed one time for each iteration of the “outer loop“

for iterating_var in sequence:

  for iterating_var in sequence:

     statements(s)

  statements(s)

.

while expression:

  while expression:

    statement(s)

  statement(s)

0 Comments

Leave a Reply

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