How do i use the for loop in python?



  • For loops in python are like many other scripting & programming languages.

    You can loop through (iterate) lists, dictionaries, tuples, and strings and perform various actions on them.

    for loops

    Here's an example of loop over a list of cakes.

    mycakes = ["victoria", "ginger", "carrot"]
    for cake in mycakes:
        print("I got " + cake + " cakes!")
    

    I got victoria cakes!
    I got ginger cakes!
    I got carrot cakes!

    You can also use the built-in function called range in for loop for repeating things a number of times. Note that the numbers do not include number 10.

    for num in range(1,10):
         print("Hello World, I'm number " + str(num))
    

    Hello World, I'm number 1
    Hello World, I'm number 2
    Hello World, I'm number 3
    Hello World, I'm number 4
    Hello World, I'm number 5
    Hello World, I'm number 6
    Hello World, I'm number 7
    Hello World, I'm number 8
    Hello World, I'm number 9

    It is important where you place your indentations For example the following two give different results.

    total  = 0
    prices = [2, 4, 6]
    for i in prices:
        total += i
    print(total)
    

    The result is:

    $ ./main.py
    12
    

    Where as the following code: The print function become part of the for loop.

    total  = 0
    prices = [2, 4, 6]
    for i in prices:
        total += i
        print(total)
    

    The result is:

    $ ./main.py
    2
    6
    12
    

Log in to reply
 

© Lightnetics 2024