FOR LOOP

FOR LOOP 

In Python, a for loop is used to iterate over a sequence (such as a list, tuple, string, or range) or any iterable object. The loop iterates over each item in the sequence and executes a block of code for each iteration. The general syntax of a for loop in Python is as follows


SYNTAX:

for item in sequence:
    # code block to be executed for each item

Here's a breakdown of each part:

  • In this example, variable is a placeholder representing the loop variable that will take on each value from the sequence during each iteration of the loop. The loop will continue executing the code block until it has processed all the elements in the sequence.

    Let's see a specific example in Python where we use a for loop to print the numbers from 1 to 5:

  • EXAMPLE CODE:

  • for i in range(1, 6): print(i)

  • OUTPUT:

  • 1

    2

    3

    4

    5

  • In this example, range(1, 6) generates a sequence of numbers from 1 to 5 (inclusive). During each iteration, the loop variable i takes on the next value from the sequence, and the print(i) statement outputs the value of i to the console.

    You can customize the behavior of a for loop based on your requirements. The sequence can be a range of numbers, a list, a string, or any iterable object depending on the programming language you are using.




Comments

Popular posts from this blog

Fibonacci Series

COMPARISION EXPRESSION

LOGICAL EXPRESSION