Python For Loop

Loops are used to repeat a block of code multiple times.

“for” loop in python is used when the number of repetition is known.

“while” loop is used when the number of repetition is not known in advance, or can be infinite but there have to be a condition for stopping or exiting out the loop.

Example 1

Inthis example, x takes values from 0 to 4, using the range() method.

The range() method returns an interable object, allowing us to loop through elements one at a time.

   for x in range(5): print("data")

Let’s see whats inside the range(5)

  list(range(5))
   for x in range(5): print("data", x)

Example 2 - Range between two numbers

Here, x starts at 3 and stops before 5.

This shows how the rnge(start, stop) allows us to define a custom starting point, with the loop stopping just before the stop value

   for x in range(3, 5): print("data", x)

Example 3 - Step

Here, the loop starts at 2 and goes up to (but does not include) 10, increasing by 2 each time.

The third argument in range(start, stop, step) controls the interval between values.

we can skip items, or count by custop steps.

   for x in range(2, 10, 2): print("data", x)

Move backwards - two ways to do this

This loop counts down from 4 to 0.

It starts at 4, stops just before -1, and decreases by 1 step each time.

   for x in range(4, -1, -1): print("data", x)

Here we use the builtin reversed() method to reverse the list.

   for x in reversed(range(5)): print("data", x)

Next Set of Examples Break and Continue

break:

This loop startsfrom 2 and stops when i * 5 becomes greater than 10.

The break statement immediately exits the loop once the condition is met.

   for i in range (2, 10): if i * 5 > 10: break print(i)
continue

This loop sips printing the number when i * 5 equals 15 (i.e, when i is 3)  using the continue statement.

   for i in range (2, 10): if i * 5 == 15: continue print(i)

We can also use for loop to loop through strings in python.

   for x in "Sci-Kit Learn": print(x)

we pass in another argument to the print called “end” and this seperate the looped string by “|”

   for x in "Sci-Kit Learn": print(x, end="|")

We can also loop over a list using the for loop.

his is the most common use case of the for loop.

  #for loop in lists for x in ['train test split', 'regression', 'classification', 'random forest']: print(x)
  baseball_teams = ['Rays', 'Yankees', 'Red Sox']
   for team in baseball_teams: print(team)

The enumerate() method gives both the index and the value at each step of the loop.

note, the index starts at 0.

   for index, letter in enumerate(baseball_teams): print(index, letter)
  baseball_player = {'name': 'Nolan Ryan', 'team': 'Astros', 'Position': 'pitcher', 'number':'34'}

Here we loop through the baseball_player dictionary values using the .values() method and we print out the values.

   for data in baseball_player.values(): print(data)

Here we iterate over each key-value pair in the dictionary baseball_player.

Using the .item() method, we access both the key and value simultaneously during iteration.

   for key, value in baseball_player.items(): print(key, ':', value)

Nested loop - one loop in another

A nested loop is a loop inside another loop.

In this code, the inner loop runs completely for each iteration of the outer loop.

The outer loop runs x from 0 to 6,

for each x, the inner loop runs y from 0 to 8

   for x in range(7): for y in range(9): print(f"{x} {y}")
  runners = ['Kipchoge', 'Ownes', 'Nurmi'] distances = ['5k', '10k', 'marathon']

This nested loop prints every combination of runner and distance.

It’s a simple way to pair items from two lists and show all possible matches.

   for runner in runners: for distance in distances: print(runner + ': ' + distance)

Using for Loops to sum

Here, we add the square of each number from 0 to 4 to the initial sum of 100.

Then we print the updated total at each step of the loop

  sum = 100 for x in range(5): sum = sum + x*x print(sum)

Here, we add each number from the list to the starting sum of 50,Â

Then we print the running total after each addition in the loop.

  list = [22, 55, 88] sum = 50 for number in list: sum = sum + number print(sum)

Ryan is a Data Scientist at a fintech company, where he focuses on fraud prevention in underwriting and risk. Before that, he worked as a Data Analyst at a tax software company. He holds a degree in Electrical Engineering from UCF.

Leave a Reply

Your email address will not be published. Required fields are marked *