
- 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:
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:
So far it should be clear. Now let's look at different examples.
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.
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:
You get This:
3️⃣Example: For-Loop with Numbers
Now let's iterate over numbers. For example:
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:
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:
💡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():
And you can even specify the step between start and end numbers.
Let's make it more useful. Let's use these numbers to create list of floor plan names:
And now you get a list of FloorPlans:
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.
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.
⭐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!
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.
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:
➿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:
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.
This will give you this result:
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:
This will create an infinite loop because we set our condition to True! 
Let's change that to another logic:
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:
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.
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.
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.
Sposored by LearnRevitAPI.com





