Resources
Lesson Objectives
What are loops?
How to create Loops in Python?
The power of repeating your code
Loop Examples
Are you Ready?
Summary
What are Loops in Python?
It's time to talk about loops in python and they are a very essential concept to solve repetitive problems.
Loops allow you to execute the same piece of code over and over depending on a condition or size of the collection. Therefore the name - Loop.
In python there are 2 types of loops:
For-Loop - Creates a loop FOR EACH item in a collection.
While-Loop - Create a loop until condition is 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.
🧠Imagine This
You select multiple sheets in Revit and then you want to go one by one and print a PDF. (That’s a loop)
Or maybe you selected something in Revit UI, and you want to check a parameter before you do something with each item. (You guessed it, that's also a loop).
For-Loops allow you to execute the same piece of code with logic on each item in a collection, no matter how many items you have.
It's a crucial concept concept you need to understand, because you will constantly be working with list of items in Revit API and you would want to create loops with them. But don't worry, it's a simple one as well.
Python Syntax: For - Loops
So, how do we create for loops in python?
To create a loop we need to do the following:
Use
for
keyword to initiate for-loop.Specify
variable
name (used for each item)Specify 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 print them. We can do far more than that, but let's keep it simple for now.
You can see that for-loops also need a code block. But this code block will be executed for each item in a container.
Variable Name in For-Loops
As I've mentioned you need to specify variable name after for
keyword.
You can name this variable anything you want, and it will reference each item in the collection one by one and execute the code block. Many use simple i
letter to create a quick for-loop.
💡It doesn't matter what you name your variable. What matters is that each item in a collection will be referenced one by one using that variable name.
So in the example above, firstly i
will represent number 1
and in the first iteration it will make 3 print statements of that number (1 1 1).
Then, once the iteration is over, i
will become number 2
and it will execute the same code block again. So this time (2 2 2).
And so on…
💡You can also add if-statement, to make a logical check on each item, to make sure you execute certain piece of code only if item matches your condition.
A Few Definitions
Now let me break down a few definitions that you might hear in programming.
Iteration: The process of repeatedly executing a block of code for each item in a sequence. Think of loops
Sequence: An ordered collection of items that supports iteration, such as a list, tuple, or string.
Iterable: An object capable of returning its elements one at a time, making it possible to iterate over. It includes sequences but also other unordered types like set and dictionary.
For-Loop with Lists
Alright, let's put it in a perspective and create more for-loops.
Imagine you have a list of materials and you want to display them in a console one by one. That's a very common command you will execute.
Here is an 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.
Let's iterate through each character and make out print statement a bit more interesting.
You get This:
For-Loop with Numbers
Alright, let's see how can we iterate through numbers.
Let's try that one:
And we hit the wall…
Firstly, don't be afraid of seeing error messages in programming.
It doesn't mean that you crashed your PC. It just means that you've encountered an error, and there wouldn't be any programmers without them. How else would they know that they did something wrong?
As you can see, the int
is not iterable object. It means, we can not iterate through numbers. And it kind of makes sense.
So, instead, we need to convert number into something else if we want to iterate through each number.
Here is a workaround:
Let's break down what's going on:
We convert number into a string (
"123456789"
)Convert each number back into integer (
int()
)Make Calculation
It adds an extra step, but we get the result that we wanted.
For-Loop with range()
What if we wanted to iterate through number differently?
We didn't want to get each number, but we wanted to create n-amount of loops. How do we do that?
Well, for that we can use a built-in function called range()
. It can create a list of numbers by providing max number.
Like this:
Firstly, notice that we always start counting in python with 0, therefore we get a list of numbers from 0-9. There are ten digits in total.
It's also very common to use this to create for-loop with n-number of iterations.
For Example:
This would print a list of FloorPlans with nubmers in the end like:
Break out of loops
Another important thing you should know about loops, is that you have an ability to break them any time. And you would use a 'break'
keyword for that.
Usually, you would create a loop where you look for something, or you have some sort of limit. And once you find the item you need, or you hit the limit you want to start iteration.
For example, imagine that you have a list of line-patterns (it can be 4, or can be 1000). So, you can iterate through all items and then check if you have a pattern with a name 'solid' and then save it under solid_pattern
variable.
So here is a simplified version of that code:
Also notice that I've defined solid_pattern = None
.
That's important because if your if-statement
never get True
(meaning no match), then this code block will never be executed. So it means that the line solid_pattern = pat
might not execute, so you won't be able to use it later.
Therefore, it makes sense to define solid_pattern
as None
, so we don't get a syntax error (missing variable), instead we just see that solid_pattern = None
This example might be a bit confusing, because I use strings in a list. But let's have a look at a Revit API code snippet that would actually get all patterns and look for solid pattern. (No need to copy code, just compare it visually to understand logic)
Don't worry if you find it hard. There are Revit API concepts present.
You will learn Revit API basics in the next module, and it won't be so hard, I promise.
For now, just focus on python basics!
While loops (not recommended )
Alright, lastly I want to briefly mention while
loops.
While loops allow you to create loops until certain condition is satisfied. However, they can also become infinite loops if you never reach the condition.
They are not so complicated, however beginners always forget to create the right condition so the loop ends eventually. And if you create an infinite loop, it won't stop on its own, you will have to terminate your command.
It's not an issue in code-editors. However, if you create an infinite loop in Revit, you would need to close Revit with Task Manager… And it's never fun. So try to avoid using them, or at least triple check that your condition is correct.
How do we make a condition? Similar to if-statements.
For example, here is a very simple while loop that will run, until x
value is less than 10.
In this case, you can see that I'm using x+=1
that will keep incrementing x, so it actually grows. And eventually it will go beyond 10 and loop will end (because condition was satisfied).
However, if you somehow forget to add this x+=1
line, then you will create an infinite loop where you will print
x
value until you terminate the command….
Why we need while-loops then?
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 are selling tickets and you have a limit of 100. You could think that you would need 100 iterations, but some people come and buy multiple tickets (2,5,10+). So you don't know how many customers you need to sell all 100 tickets.
So, you create a while loop and then ask user to specify how many tickets they want to buy. And then you update your counter to that number.
This way, you have a loop that will keep asking user how many tickets to sell, and then keep track until all tickets are sold.
Here is the code to do that, try to execute it as well:
HomeWork
Alright, and that's a wrap on the loops.
I highly recommend you to go through the code and try it yourself.
You need to practice yourself to get into a habit of using these concepts. These are key concept that you will use over and over again.
You can watch me all day long, but if you try it a few times, you will learn and remember it much better. Try it.
And once you are done, we will see each other in the next lesson.
⌨️ Happy Coding!