🚧Summaries For Lessons 24+ Are Still Work In Progress!

“Whoever is patient has great understanding…" Proverbs 14:29

How To Use Loops in Python

Description here...

How To Use Loops in Python

Description here...

How To Use Loops in Python

Description here...

- What are loops?
- How to create Loops in Python?
- The power of repeating your code
- Loop Examples

Loops in Python

Alright, it's time to talk about loops in python.
Alright, it's time to talk about loops in python.
Alright, it's time to talk about loops in python.

Hold on, is that a LOOP🤯? Exactly!

Loops allow you to execute the same piece of code over and over on your data. You can also add logic to do different things depending on the values (more on that later.)

Loops are essential concept in python and there are 2 types:

  • For-Loop - Creates a loop FOR EACH item in a collection.

  • While-Loop - Create a loop WHILE CONDITION is not satisfying (can be infinite too…)

We will focus 90% on the for-loops, because that's what you need the most. While-loop is good to know about, but I recommend you to avoid them if possible because beginners get stuck in the infinite loops all the time...

🟦 For-Loop Basic Syntax

So let's start with the basics. How do we create a loop?

To create a loop we need to do the following:

🔹Use for keyword to initiate for-loop.
🔹Specify any variable name (used for each item)
🔹Point to a Container (list, tuple, dict, str…)
🔹Create Code-Block (Code for each iteration)

Here is an example:

container = [1,2,3]

for i in container:
    print(i)
    print(i)
container = [1,2,3]

for i in container:
    print(i)
    print(i)
container = [1,2,3]

for i in container:
    print(i)
    print(i)

This simple code will iterate over each item in a container and then execute code block for each item. In this case, it will print each number twice.

We can do far more than that, but let's keep it simple for now.

📦Variable Name in For-Loops

As you've seen - we need to specify a variable name (e.g. i ) after for keyword. And then this variable will have different value on each iteration from the container that you pointed to.

So on first iteration i=1, then i=2 and so on until you go over all items in the container.

💡You can use any variable name! i is just a default placeholder many use. Just make sure you reference the same name in your code block.

🧠Logic inside For-Loop

While you're iterating over items you can add more logic to decide what to do. This way you can achieve a lot by using Loops + Logic.

For example, let's check the value of each item and if it's 2 then we'll make an additional print statement:

container = [1,2,3]

for num in container:
    print(num)
    print(num)
    print(num)

    if num == 2:
        print('Number Two')
container = [1,2,3]

for num in container:
    print(num)
    print(num)
    print(num)

    if num == 2:
        print('Number Two')
container = [1,2,3]

for num in container:
    print(num)
    print(num)
    print(num)

    if num == 2:
        print('Number Two')

So far it should be clear. Now let's look at different examples.

Sign-Up For Future Updates✨

Be among the first people to hear about
New Python Courses or Useful Resources!

Once there's enough demand I might start a Python Newsletter
with even more Tips and Tricks to help you learn it better!


Want To Donate? Click here.

Sign-Up For Future Updates✨

Be among the first people to hear about
New Python Courses or Useful Resources!

Once there's enough demand I might start a Python Newsletter
with even more Tips and Tricks to help you learn it better!


Want To Donate? Click here.

Sign-Up For Future Updates✨

Be among the first people to hear about
New Python Courses or Useful Resources!

Once there's enough demand I might start a Python Newsletter
with even more Tips and Tricks to help you learn it better!


Want To Donate? Click here.

1️⃣ Example: For-Loop with Lists

Imagine you have a list of materials and you want to display them in a console one by one. That's a very common use of for-loops with lists.

list_materials = ['Wood', 'Steel', 'Glass', 'Bricks']

for mat in list_materials:
    print(mat)
    print(mat.lower(), mat.upper()) #Turn all characters into Lower/Upper
list_materials = ['Wood', 'Steel', 'Glass', 'Bricks']

for mat in list_materials:
    print(mat)
    print(mat.lower(), mat.upper()) #Turn all characters into Lower/Upper
list_materials = ['Wood', 'Steel', 'Glass', 'Bricks']

for mat in list_materials:
    print(mat)
    print(mat.lower(), mat.upper()) #Turn all characters into Lower/Upper

Here's the result in the console:

2️⃣ Example: For-Loop with Strings

We can also iterate through strings, because if you think about it, it's an ordered collection of alphanumeric characters. So let's print each character in a string:

for char in "Hello Python Hackers!":
    upper_letter = char.upper()
    lower_letter = char.lower()
    print(lower_letter, '---', upper_letter)
for char in "Hello Python Hackers!":
    upper_letter = char.upper()
    lower_letter = char.lower()
    print(lower_letter, '---', upper_letter)
for char in "Hello Python Hackers!":
    upper_letter = char.upper()
    lower_letter = char.lower()
    print(lower_letter, '---', upper_letter)

You get This:

h --- H
e --- E
l --- L
l --- L
o --- O
  ---  
p --- P
y --- Y
t --- T
h --- H
o --- O
n --- N
  ---  
h --- H
a --- A
c --- C
k --- K
e --- E
r --- R
s --- S

h --- H
e --- E
l --- L
l --- L
o --- O
  ---  
p --- P
y --- Y
t --- T
h --- H
o --- O
n --- N
  ---  
h --- H
a --- A
c --- C
k --- K
e --- E
r --- R
s --- S

h --- H
e --- E
l --- L
l --- L
o --- O
  ---  
p --- P
y --- Y
t --- T
h --- H
o --- O
n --- N
  ---  
h --- H
a --- A
c --- C
k --- K
e --- E
r --- R
s --- S

3️⃣Example: For-Loop with Numbers

Now let's iterate over numbers. For example:

big_number = 123456789

for num in big_number:
    print(num)
big_number = 123456789

for num in big_number:
    print(num)
big_number = 123456789

for num in big_number:
    print(num)

And you get an error...

But don't worry.

It's totally normal to see errors while you code. It just means that you've made a mistake and it tells you exactly what went wrong and on which line. You'll learn a lot from errors.

In this case you can see that it happened on line 35 and it's Type Error: 'int' object is not iterable . Now you know where to look and what's the issue.

Not Iterable - means that we can not loop over this kind of object. And it makes sense, it's just a number. So we need to convert it into something that we can iterate over - for example strings.

Here is a workaround:

big_number = 123456789

for str_num in str(big_number):
    num  = int(str_num)
    sq   = num*num
    cube = num**3
    print(num, sq, cube)
big_number = 123456789

for str_num in str(big_number):
    num  = int(str_num)
    sq   = num*num
    cube = num**3
    print(num, sq, cube)
big_number = 123456789

for str_num in str(big_number):
    num  = int(str_num)
    sq   = num*num
    cube = num**3
    print(num, sq, cube)

Let's break down what's going on:

  • We convert big number into a string ("123456789")

  • Convert each number back into integer ( int() )

  • Make Calculation

It adds an extra step, but that's how we get the result we wanted.

4️⃣ For-Loop with range()

While working with for-loop you'll often want to use built-in range() function. It can be really useful to create a sequence of numbers to iterate over.

For example you can print each number, or execute the same block over and over using this syntax:

# Print Each Number
for i in range(10): # [0,1,2,3,4,5,6,7,8,9]
    print(i)

# Same Code-Block
for i in range(5):
    print('Hello World')
# Print Each Number
for i in range(10): # [0,1,2,3,4,5,6,7,8,9]
    print(i)

# Same Code-Block
for i in range(5):
    print('Hello World')
# Print Each Number
for i in range(10): # [0,1,2,3,4,5,6,7,8,9]
    print(i)

# Same Code-Block
for i in range(5):
    print('Hello World')

💡Remember that counting in Python always starts from 0. That's why we get 0-9 numbers.


You can also specify the Start and End number in the range():

for i in range(10,20):
    print(i)               # Numbers 10-19
for i in range(10,20):
    print(i)               # Numbers 10-19
for i in range(10,20):
    print(i)               # Numbers 10-19

And you can even specify the step between start and end numbers.

for i in range(0, 101, 10):
    print(i)           # 0, 10, 20...
for i in range(0, 101, 10):
    print(i)           # 0, 10, 20...
for i in range(0, 101, 10):
    print(i)           # 0, 10, 20...

Let's make it more useful. Let's use these numbers to create list of floor plan names:

floor_plans = []

for i in range(1, 11):
    plan_name = f'FloorPlan_{i}'
    floor_plans.append(plan_name)

print(floor_plans)
floor_plans = []

for i in range(1, 11):
    plan_name = f'FloorPlan_{i}'
    floor_plans.append(plan_name)

print(floor_plans)
floor_plans = []

for i in range(1, 11):
    plan_name = f'FloorPlan_{i}'
    floor_plans.append(plan_name)

print(floor_plans)

And now you get a list of FloorPlans:

FloorPlan_1
FloorPlan_2
...
FloorPlan_9
FloorPlan_10
FloorPlan_1
FloorPlan_2
...
FloorPlan_9
FloorPlan_10
FloorPlan_1
FloorPlan_2
...
FloorPlan_9
FloorPlan_10

Example: Loop Over Dict

We can also iterate over dictionaries. If you write for i in dict then i will take key names of each item in a dictionary.

my_dict = {'key1' : 'value1',
           'key2' : 'value2',
           'key3' : 'value3',
           }

for i in my_dict:
    print(i) # key1...
my_dict = {'key1' : 'value1',
           'key2' : 'value2',
           'key3' : 'value3',
           }

for i in my_dict:
    print(i) # key1...
my_dict = {'key1' : 'value1',
           'key2' : 'value2',
           'key3' : 'value3',
           }

for i in my_dict:
    print(i) # key1...

In case you want to iterate over values, then you'd need to use values() method on your dictionary to get a list of values.

my_dict = {'key1' : 'value1',
           'key2' : 'value2',
           'key3' : 'value3',
           }

for i in my_dict.values():
    print(i) # value1...
my_dict = {'key1' : 'value1',
           'key2' : 'value2',
           'key3' : 'value3',
           }

for i in my_dict.values():
    print(i) # value1...
my_dict = {'key1' : 'value1',
           'key2' : 'value2',
           'key3' : 'value3',
           }

for i in my_dict.values():
    print(i) # value1...

⭐Pro Tip: You can also iterate over keys and values at the same time. For that you'll need to get keys and values as tuples with .items() method. It's very common!

my_dict = {'key1' : 'value1',
           'key2' : 'value2',
           'key3' : 'value3',
           }

for k,v in my_dict.items():
    print(f'Key: {k}')
    print(f'Value: {v}')
my_dict = {'key1' : 'value1',
           'key2' : 'value2',
           'key3' : 'value3',
           }

for k,v in my_dict.items():
    print(f'Key: {k}')
    print(f'Value: {v}')
my_dict = {'key1' : 'value1',
           'key2' : 'value2',
           'key3' : 'value3',
           }

for k,v in my_dict.items():
    print(f'Key: {k}')
    print(f'Value: {v}')

Notice that we can define 2 variables k,v because .items will produce pairs in a tuple like [('key1', 'value1), ('key2', 'value2)...]

⛓️‍💥Break out of loops

Sometimes you don't need to iterate over all items. Maybe you start searching for something in a list, and once you find it there's no need to continue iterating. For that we need to use break keyword.

Once you execute break, it'll immediately stop the execution of the loop and continue with the code you have after the loop.

For example let's find the first even number in a list of numbers.

nums = [0, 99, 1, 23, 33, 40, 57, 6, 81,]

for n in nums:
    if n%2 == 0 and n!= 0:
        print(f'First Even Number: {n}')
        break

print('Finished.')
nums = [0, 99, 1, 23, 33, 40, 57, 6, 81,]

for n in nums:
    if n%2 == 0 and n!= 0:
        print(f'First Even Number: {n}')
        break

print('Finished.')
nums = [0, 99, 1, 23, 33, 40, 57, 6, 81,]

for n in nums:
    if n%2 == 0 and n!= 0:
        print(f'First Even Number: {n}')
        break

print('Finished.')

That's how you can find the first even number.

If you'd comment out break keyword and run it, you'll find multiple even numbers and it won't make sense with this print statement.

So break statement can be great for searching for something or creating a condition until when we can execute the loop.

➡️ Continue iteration

Another interesting keyword we can use inside of loops - continue. Instead of breaking out of the loop, we can skip a single iteration.

You can also achieve the same result with an additional if-statement. But sometimes continue can make your code more readable.

For Example:

real_money = (5, 10, 20, 50, 100, 200, 500) # EUR
wallet     = [5, 20, 10, 25, 10, 50]

total = 0
for note in wallet:
    if note not in real_money:
        continue

    total += note

print(f'Total: {total} EUR')
real_money = (5, 10, 20, 50, 100, 200, 500) # EUR
wallet     = [5, 20, 10, 25, 10, 50]

total = 0
for note in wallet:
    if note not in real_money:
        continue

    total += note

print(f'Total: {total} EUR')
real_money = (5, 10, 20, 50, 100, 200, 500) # EUR
wallet     = [5, 20, 10, 25, 10, 50]

total = 0
for note in wallet:
    if note not in real_money:
        continue

    total += note

print(f'Total: {total} EUR')

➿Nested Loops

Now lastly, we can also create nested for-loops. So we'll create a loop inside of a loop.

For example we could iterate over nested lists like this:

course = [
	['Lesson_01.01', 'Lesson_01.02', 'Lesson_01.03', 'Lesson_01.04'],
	['Lesson_02.01', 'Lesson_02.02', 'Lesson_02.03'],
	['Lesson_03.01', 'Lesson_03.02']
]

for module in course:
    print(f'Starting Module: {module}')

    for lesson in module:
        print(f'Completed: {lesson}.')

    print('Module is Compelte!')
    print('-----')
course = [
	['Lesson_01.01', 'Lesson_01.02', 'Lesson_01.03', 'Lesson_01.04'],
	['Lesson_02.01', 'Lesson_02.02', 'Lesson_02.03'],
	['Lesson_03.01', 'Lesson_03.02']
]

for module in course:
    print(f'Starting Module: {module}')

    for lesson in module:
        print(f'Completed: {lesson}.')

    print('Module is Compelte!')
    print('-----')
course = [
	['Lesson_01.01', 'Lesson_01.02', 'Lesson_01.03', 'Lesson_01.04'],
	['Lesson_02.01', 'Lesson_02.02', 'Lesson_02.03'],
	['Lesson_03.01', 'Lesson_03.02']
]

for module in course:
    print(f'Starting Module: {module}')

    for lesson in module:
        print(f'Completed: {lesson}.')

    print('Module is Compelte!')
    print('-----')

This way we can go over each list of lessons that represents a module and then over each lesson inside that list.


Alternatively, we can also use nested loops to generate pairs of numbers.

For example, let's create a list of XY coordinates where we get all combinations of X and Y.

for x in range(3):
    for y in range(3):
        print(x,y)
for x in range(3):
    for y in range(3):
        print(x,y)
for x in range(3):
    for y in range(3):
        print(x,y)

This will give you this result:

0 0
0 1
0 2
1 0
1 1
1 2
2 0
2 1
2 2
0 0
0 1
0 2
1 0
1 1
1 2
2 0
2 1
2 2
0 0
0 1
0 2
1 0
1 1
1 2
2 0
2 1
2 2

Notice that at first X stays 0 while we're going through all Y values. This is because Y loop is inside of X loop. I hope it makes sense...

🔁 While Loops

Lastly I want to briefly mention while loops.

For-Loops are great to use on a container with a fixed length (e.g. 10 items in a list)

While-Loops are great for iterating until certain condition is satisfied. It can be 1 iteration or 100 iterations - all depends on your logic.

Also be carteful as they can turn into infinite loops if you don't define your condition very well. It won't stop on its own so you'll have to manually stop code execution. And let's start with an infinite loop:

count = 0
while True:
    print('Attempt: ', count)
count = 0
while True:
    print('Attempt: ', count)
count = 0
while True:
    print('Attempt: ', count)

This will create an infinite loop because we set our condition to True!
Let's change that to another logic:

count = 0
while count < 10:
    print('Attempt: ', count)
    count += 1
count = 0
while count < 10:
    print('Attempt: ', count)
    count += 1
count = 0
while count < 10:
    print('Attempt: ', count)
    count += 1

Now, we'll execute until count reaches 10. And don't forget to increase count += 1 . Otherwise you can get stuck in infinite loop again.

Alternatively, you can create infinite loop and then stop it with a break statement. Here's example:

count = 0
while True:
    if count == 100:
        break

    print('Attempt: ', count)
    count +=1
count = 0
while True:
    if count == 100:
        break

    print('Attempt: ', count)
    count +=1
count = 0
while True:
    if count == 100:
        break

    print('Attempt: ', count)
    count +=1

Why we need while-loops ?

Sometimes while-loops are amazing. You just need to be careful to reach your conditions to avoid infinite loops. The most common use-case is when you don't know how many times you need to execute your loop.

✨Imagine This:

You have 100 tickets to sell but you don't know how many customers you'll get.

Some will get 1-2 tickets, while somebody might get 10 tickets. Therefore we'll have different number of iterations.

Let's create a loop and then ask user how many tickets they'd like to buy. And it will run until we're sold out.

tickets = 100

while True:
    n = input('Buy Tickets: ')
    n = int(n)

    # Ensure enough tickets to sell
    if tickets - n < 0:
        print('⚠️Not enough tickets. Try again.')
        continue

    # Sell Tickets
    tickets -= n
    print(f'Tickets Left: {tickets}')

    if tickets == 0:
        print('Sold Out!')
        break
tickets = 100

while True:
    n = input('Buy Tickets: ')
    n = int(n)

    # Ensure enough tickets to sell
    if tickets - n < 0:
        print('⚠️Not enough tickets. Try again.')
        continue

    # Sell Tickets
    tickets -= n
    print(f'Tickets Left: {tickets}')

    if tickets == 0:
        print('Sold Out!')
        break
tickets = 100

while True:
    n = input('Buy Tickets: ')
    n = int(n)

    # Ensure enough tickets to sell
    if tickets - n < 0:
        print('⚠️Not enough tickets. Try again.')
        continue

    # Sell Tickets
    tickets -= n
    print(f'Tickets Left: {tickets}')

    if tickets == 0:
        print('Sold Out!')
        break

Here's the breakdown:

🔹Define tickets = 100
🔹Create While-Loop
🔹Ask how many tickets?
🔹Ensure enough tickets available
🔹Sell Tickets
🔹Check if Sold out (break if yes)

Try it out!

It's a great example on how and when to use while-loops in python. Just make sure you double check all your conditions to avoid infinite loop. And don't worry, if you create one, just click CTRL+D to cancel it in the console or look for a red stop button.

Happy Coding!

🙋‍♂️ See you in the next lesson.
- EF

Happy Coding!

🙋‍♂️ See you in the next lesson.
- EF

Happy Coding!

🙋‍♂️ See you in the next lesson.
- EF

As you've guessed it - now it's your turn.

Go along the code and try it out yourself. You need to understand loops because you'll need them all the time.

Also, you won't learn by watching me do it all day long. Instead you'll learn 10X if you do it yourself.

⌨️ Happy Coding!

⌨️ Happy Coding!

⌨️ Happy Coding!

If you have any questions, leave them in the YouTube Comments.

If you have any questions, leave them in the YouTube Comments.

If you have any questions, leave them in the YouTube Comments.

Have a Question?

Have a Question?

Have a Question?

Sign-Up For Future Updates✨

Be among the first people to hear about
New Python Courses or Useful Resources!

Once there's enough demand I might start a Python Newsletter
with even more Tips and Tricks to help you learn it better!


Want To Donate? Click here.

Sign-Up For Future Updates✨

Be among the first people to hear about
New Python Courses or Useful Resources!

Once there's enough demand I might start a Python Newsletter
with even more Tips and Tricks to help you learn it better!


Want To Donate? Click here.

Sign-Up For Future Updates✨

Be among the first people to hear about
New Python Courses or Useful Resources!

Once there's enough demand I might start a Python Newsletter
with even more Tips and Tricks to help you learn it better!


Want To Donate? Click here.

PS. Python can change your career and how you think about problems.
Be Careful 🙂

PS. Python can change your career and how you think about problems.
Be Careful 🙂

PS. Python can change your career and how you think about problems.
Be Careful 🙂

Sposored by LearnRevitAPI.com