For loop

 The for loop executes code repeatedly until the condition for it is no longer valid.


We loop through an iterable with the for loop. An iterable refers to anything that can be looped over, such as a string, list or tuple.

Example

food = ["rice", "chicken", "chocolate", "peanut butter"]

for favFood in food:

    print(favFood)

In the program above, the list food is declared and has items "rice", "chicken", "chocolate" and "peanut butter". Next, the statement for favFood in food: loops through the food list and assigns each item in the list to the variable favFood. So, in this example, the program runs through the for loop and assigns "rice" to the variable favFood; runs through the for loop again and assigns "chicken" to the variable favFood and so on. The program continues looping through the list until the end of the list is reached.


Output

rice

chicken

chocolate

peanut butter


We can also display the index of the items in the list. We use the enumerate() function to do so.


for index, favFood in enumerate(food):

    print(index, favFood)

Output

0 rice

1 chicken

2 chocolate

3 peanut butter


We can also loop through strings.

message = "yes"

for i in message:

    print(i)


Output

y

e

s


We can also loop through a sequence of numbers. To loop through a sequence of numbers, the range() function comes in handy. It generates a list of numbers and has the syntax range (start, end, step). If start is not given, the numbers generated will start from zero.


If step is not given, a list of consecutive numbers will be generated. The end value must be provided. However, an unusual thing about the range() function is that the given end value is never part of the generated list.

Examples

range(5) will give the list [0, 1, 2, 3, 4]

range(3, 10) will give [3, 4, 5, 6, 7, 8, 9]

range(4, 10, 2) will give [4, 6, 8]


This is how the range() function works in a for statement.

for (i) in range(4)

    print(i)

Output

0

1

2

3

No comments:

Post a Comment