Post

Loops Explained - Using for and while in Python

Loops in any programming language form the crux of repetitive code. Repetitive code is used to perform consecutive code operations, which help solve problems such as creating counters or iterators. On Day 10, I’ll be learning all about repetitive code and loops.

Loops Explained - Using for and while in Python

Today’s topic is intriguing to say the least. Loops are essential to any program, regardless of the language you use. We need loops to perform operations like sorting and inserting, which help us refine data and then perform other operations on that. Consider a scenario where we need to sort an array of data, such as numbers, and this cannot be done in a single iteration; it must be accomplished over multiple iterations.

We would have to factor in how the algorithm will know it has the largest number selected. We would also think about how it would allocate a position for the selected number to be placed in. Finally, it would then need to select the next integer to perform the same operations on.

On smaller fragments of data, this may take a split second to do. On larger and more complex data structures, this could take significant time. This is where and why we learn about DSA.

In Python, we use two different types of loops:

  1. While Loops
  2. For Loops

While Loops

While loops are used to have specific blocks of code execute repeatedly while a specified condition remains True.

You can escape a While loop by having the condition turn to False or using break.

A while back, I mentioned reserved words, words that are used for built-in functions and shouldn’t be used for other things, like creating variables. These are included in that list.

1
2
while condition: # condition is set here
  code # Block of code here

To better illustrate the coding syntax above.

1
2
3
4
5
6
7
8
count = 0

while count < 10:
  print(count)
  count += 1

  # Will print from 0 to 9
# Next lines of code after the loop is complete

Like If Statements1, we can use an else clause to specify a piece of code that would run once the condition has been fulfilled or set to false in while loops.

1
2
3
4
5
6
while condition:
  recursive code
else:
  close code

new code line

Think of it as being a method to have the while condition end a little more naturally.

1
2
3
4
5
6
7
8
count = 0
while count < 10:
    print(count)
    count = count + 1
else:
    print(count)

# This now prints to 10

Using If Statements In a Loop

Having if statements within loops is what we use to gain a deeper level of sophistication. It allows us to have a decision-making process that makes our code more lively and responsive.

1
2
3
4
while condition:
  code
  if condition:
    code

For Loops

A for loop can be used to iterate through a sequence like a list, a tuple, a dictionary, or a string. For each character or item in your data, this loop will execute.

1
2
for each_item in range/list:
  Do this code

Creating a for loop requires that you specify a variable that is used on each iteration and the sequence to work from.

1
2
3
4
5
6
7
8
9
for char in "Python":
  print(char)

  #P
  #y
  #t
  #h
  #o
  #n

What I found particularly helpful by this point was being able to explore what I can do on each iteration by using different data types and variables for a loop function. I used lists, dictionaries, integers, and floats to practise learning for loops.

Code Wars is an amazing resource you can use to practise Python coding

While on this topic, I should discuss the range() function, which is commonly found in for loops.

The range() function uses a similar syntax to the slicing method, range(start, stop, step).

1
2
3
4
5
6
7
8
9
10
11
12
13
for x in range(10):
  print(x)

# This will print from 0 to 9 (0-indexed)

for x in range(0,10,2):
  print(x)

# 0
# 2
# 4
# 6
# 8

Nested for loops

Similar to nested if statements1, an if statement inside another, we can do the same here. Nesting for loops to perform a set of instructions on each iteration is like having an outer loop that serves as the iterator and an inner loop that performs a function on each iteration.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
person = {
'first_name': 'Asabeneh',
'last_name': 'Yetayeh',
'age': 250,
'country': 'Finland',
'is_marred': True,
'skills': ['JavaScript', 'React', 'Node', 'MongoDB', 'Python'],
'address': {
'street': 'Space street',
'zipcode': '02210'
}
}

for key in person:
  if key == 'skills':
    for skill in person['skills']:
      print(skill) # This will print each item in the list inside of 'skills'.

Taken from the course

For, Else

for, else is used to have a loop finish with an ending sequence, if it doesn’t encounter a break.

In pythonic syntax, it would read something like this.

1
2
3
4
5
6
for each item in collection:
  do something
  if some condition:
    break
else:
  Do something if the loop did not break

Here’s an actual example:

1
2
3
4
5
6
7
8
numbers = [1, 2, 3, 4, 5]

for num in numbers:
  if num == 10:
    print("Found 10!")
    break
else:
  print("10 was not found in the list")

Using ‘Break’ and ‘Continue’

This is still a fairly new concept to me, and I would describe myself as being in the early phases of being able to create code with them. A break is used as an escape clause in a loop. If you want to exit a loop at any time, you would use this. Think of having an infinite loop like this one:

1
2
3
4
5
6
7
8
9
10
11
count = 0

while True:
  print(count + 1)
  count += 1

# 1
# 2
# 3
# 4
# 5...

This program would print infinitely, which we don’t want. Instead, we can intercept the code using a break clause when a specific condition is met using an if statement.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
count = 0

while True:
  print(count + 1)
  count += 1
  if count >= 10: # break condition
    break
print("new line of code")

#0
#1
#2
#3
#4
#5
#6
#7
#8
#9
#10
#new line of code

Now, once our counter reaches 10, we can exit the loop and begin the new line of code.

Note: The indents are places carefully throughout and indicate where each code block belong.

Continue

Where a break would exit out of a code, continue would skip an iteration for whatever purpose you have. In my coding experience, I wouldn’t say that I possess a great amount of knowledge about continue, but I would say that it should be used sparingly. The examples I have come across specify conditions using if statements to skip over an iteration using continue in a loop.

1
2
3
4
5
# syntax
for iterator in sequence:
  code goes here
  if condition:
    continue

Here’s an example taken from the course:

1
2
3
4
5
6
7
numbers = (0,1,2,3,4,5)
  for number in numbers:
    print(number)
  if number == 3:
    continue
  print('Next number should be ', number + 1) if number != 5 else print("loop's end") # for short hand conditions need both if and else statements
print('outside the loop')

Pass

Python has a placeholder function that does nothing. This allows developers to place it in certain parts of their code where they may later work on. It helps prevent errors, and rectify any coding syntax errors. This promotes the ability to write the coding logic first and then work on conditions and etc.

1
2
3
4
5
x = 0
while x < 10:
  print(x)
if x == 5:
  pass

The above code would still run as normal.

1
2
3
4
5
6
x = 0
while x < 10:
  print(x)
if x == 5:
  print("At 5")
  break

Now, I have completed my code, in both examples I have been able to use them and have them work fine but I was able to later implement the if condition completely.

To conclude

My second pass of this topic has increased my depth of knowledge when it comes to using loops. Functions like break, continue, and pass were fairly new to me; but by this point, I have been able to get a clearer understanding of it all. I’ve learnt where and how to use them effectively, and how to nest different loops. For those who are also learning, I would recommend that you visit each module and use the exercises as a means to practise coding with loops.

Footnote:

This post is licensed under CC BY 4.0 by the author.