Python | For Loop

For Loop in Python

A for loop is  used for iterating  over a sequence ( like list, tuple, string, set etc).
For loop used as iterator method

Syntax

for var in sequence :
statements




Explanation

In syntax show the ‘var’ variable takes value of the item from sequence  
On every iteration. Loop will continue until we reach the last value of squeence.

Example

    list1 = [1,10,31,50,88]
    for lst in list1:
        print(lst)

Output

    1
    10
    31
    50
    88



Loop through string

String is an iterable object, string contains a sequence of characters.
 
Example

    ste ="python"
    for st in ste:
        print(st)

Output

    p
    y
    t
    h
    o
    n



range() Function

A range() function generates the sequence of numbers.
A range() function , by default starting from zero, to end with specified number 
In range we can defined the start, stop and step_size 


Example

    for var in range(5):
        print(var)

Output

    0
    1
    2
    3
    4


Break Statement 

Example

    for letter in 'python':
        if letter =='h':
          break;
        print(letter)
    
Output

    p
    y
    t



Continue statement 

Example

    for val in "python":
        if val == "h":
            continue
        print(val)

    print("End of Loop")

Output

    p
    y
    t
    o
    n
End of Loop

Post a Comment (0)
Previous Post Next Post