for loops


for loops

The for loop is used when we need to execute some part of the code until the chosen condition is satisfied. The for loop is also known as a pre-tested loop. It is easier to use the for loop if the number of iteration is before known in advance. “For loop” is very effective when we have to traverse sequential

Syntax:

for < iterating_var in sequence>:
< statement>
E.g., for i in range(a, b):
   print(i)

range () function:

We can generate a sequence of respective numbers using the range() function.

range(5) will generate numeric from 0 to 4(5 numbers).

We can also define the start, stop, and step size included in the range(start, stop, step_size).
Default step_size value to 1 if not provided.

We can use the range() function in for loops to iterate through a sequence of numbers AS PROVIDED BY

It can also be combined with the len() function to iterate through a sequence using indexing.

We can provide anything as a range, e.g., list, tuple, dict, string, string_length, etc. We can break the for loop using the “break” keyword and giving the “if” statement conditions.
We can skip elements from the “for loop” using the “continue” keyword and giving the “if” statement conditions.
We can pass the whole “for loop” using the “pass” keyword, and it does not require an “if statement.”

Example No.1:

web= ["Knowledge2life 1", "Knowledge2life 2", "Knowledge2life 3"] for x in web: print(x)

OUTPUT:

Knowledge2life 1
Knowledge2life 2
Knowledge2life 3

Example No.2:

web = ["Knowledge2life 1", "Knowledge2life 2", "Knowledge2life 3"] for x in web: print(x) if x == "Knowledge2life 2": break

OUTPUT:

Knowledge2life 1
Knowledge2life 2