Workshop 2: Loop and Conditional Statements

  • Intro
  • Download Week 1 Jupyter Notebook
  • Conditional Statements
  • Iterations (Loops)
  • Useful Resources
  • Conclusion / Next Workshop
  • Required Readings Before Workshop 3

Information

Primary software used Python
Software version 1.0
Course Workshop 2: Loop and Conditional Statements
Primary subject Prototyping and Manufacturing
Secondary subject Robot Programming
Level Beginner
Last updated August 29, 2025
Keywords

Responsible

Teachers
Faculty

Workshop 2: Loop and Conditional Statements 0/6

Workshop 2: Loop and Conditional Statements

Learn about Python’s most powerful capabilities: loops and conditional statements!

Learning Objectives

  1. Learn how to use conditional statements to control the flow of a program
  2. Understand the concept of loops and how to use them effectively in Python
  3. Apply loops and conditional statements to solve problems

This tutorial is published as part of a series of workshops for an interfaculty course from TU Delft Faculty of Architecture and the Built Environment to support learning in and outside the class with open learning material. The intent of the workshop series is to increase familiarity with programming language Python for research and scientific applications as part of the course Creative Robotics in Spatial Design. 

You are free to go through the learning material at your own to get familiar with Python fundamentals.

Workshop 2: Loop and Conditional Statements 1/6

Download Week 1 Jupyter Notebooklink copied

Download the Jupyter Notebook here to follow along the exercises. There are two files: one with the codes already typed in them, and one without where you can manually type as you go along (Recommended).

Workshop 2: Loop and Conditional Statements 2/6

Conditional Statementslink copied

Tip: Visualize the Code Operation

For this lesson, you might find this resoruce very useful to visualize how the code is being executed. 

Python Tutor:

https://pythontutor.com/render.html#mode=display

Conditionals in Python are used to perform different actions based on different conditions (Grasshopper’s Stream Gate component comes to mind). The primary conditional statements in Python are if, elif, and else. Elif is the abbreviation of “else if”: if the “if”-condition is not met, the “elif”-condition is tested. If that one is also not met, They are constructed as follows:

if -condition a-:
  -do x-
elif -condition b-:
  -do y-
else:
  -do z-

The conditional statements form a “chain of tests”; checking each conditional statement sequentially. If a statement is met, the corresponding block of code is executed. Additionally, the chain is stopped and successive statements are not checked.

Important: the indentation on the second line is not optional In fact, VS Code might automatically add them for you if you end the line with a collon (:). They are required for code to work properly. You can manually add indentation by pressing tab or the space bar a few times. 

the code executes from the top to check for which statement is true
the code executes from the top to check for which statement is true

Consider the following code. You can see from the video on the right how the code is being executed line by line to check for each condition. 

x = 'Nither True nor False'

if x == True:
  print("x is True")
elif x == False:
  print("x is False")
else:
  print("x is", x)

Try changing x to various values, e.g. True, and False 

Note that in python, the “elif” and “else” statements are both optional
Try various values for x:

x = False

if x == True:
  print("Hello")

Changing `x` value to True will print the string “Hello”. 

“Pass” Statement

If you want an if, elif or else statement to do nothing, use “pass”
Try various values for x:

x = False

if x == True:
  pass
elif x == False:
  print("x is False")
else:
  print("x is something else")

Here is an example of if/elif/else chain to compare a and b and print whether a is smaller than, equal to, or bigger than b.

a = 5
b = 5
c = 3


if a < b:
  print("a is smaller than b")
elif a == b:
  print("a is equal to b")
else:
  print("a is not bigger than b")

 

Conditional Operators:

You can use the following operators to check for a condition: 

  • Equals: a == b
  • Not Equals: a != b
  • Less than: a < b
  • Less than or equal to: a <= b
  • Greater than: a > b 
  • Greater than or equal to: a >= b

 

Mathematical Operators in Conditional Statements

Additionally, there are various other ‘checks’ Python can run. A few examples are shown below. Values to check can be constructed in real-time with in-line formulas.

Note how 10 is divisible by 5, but it is not printed because since the “if”-condition is already met the “elif”-line is not executed:

x = 49

if x % 10 == 0:
  print(x, ": divisible by 10")
elif x % 5 == 0:
  print(x, ": not divisible by 10, but divisible by 5")
elif x % 3 == 0:
  print(x, ": not divisible by 10 or 5, but divisible by 3")
else:
  print(x, ": not divisible by 10, 5, or 3")

 

order of execution for a conditional statement
order of execution for a conditional statement

Another exmple: conditional statement to check if value is positive, negative or zero:

number = 0

if number > 0:
    print("Positive number")
elif number == 0:
    print('Zero')
else:
    print('Negative number')

Workshop 2: Loop and Conditional Statements 3/6

Iterations (Loops)link copied

The notion of iteration is very important as it is the motor that drives the automation. Iterations in Python allow you to execute a block of code multiple times. (There are other ways to do so, but we will discuss them later in the course when we look at functional programming.)

There are two main iteration techniques called loops:

  • The For loop is mostly used when the amount of time a computer need to do something is known in advance.
  • The While loop is mostly used when we don’t know how many loops should be run.

It is possible to code all iterations using only For loops or only While loops. However, it is good to get acquianted with both and to be familiar with the differences in their functioning.

A for-loop operates on an iterable object such as lists, tuples, dictionaries, etc., while a while-loop operates based on a condition such as a comparison evaluating True (like count < 10) or boolean variable remaining True. 

For-loop

The for loop in Python is used for iterating over a sequence (such as a list, tuple, dictionary, set, or string). It iterates over each item in the sequence and executes a block of code.

Python constructs the variable in the background when you call a for-loop. So you dont need to worry about that. However, it is important to understand how it really works as it might get confusing some times.

TIP: Use the Python Tutor website to visualize help you visualize how the loop is iterating through a list. https://pythontutor.com/render.html#mode=display

A flow diagram for a loop logic. source: wikipedia.
A flow diagram for a loop logic. source: wikipedia.

The structure of a for loop is as follows:

for variable_name in list_name(number of times to repeat)
     statements to be repeated

`i` is a loop variable. The letter `i` is commonly used in loops for python and other programming languages. You can think of it as the “index” in the list that Python is looping over. The list variable you want to loop over is then inserted afterwords with its own variable. Python will go over through each item and execute and operation.

Important:

  • `for` must be in lower case. `for` is not the same as `For`.
  • The statements/operations must be indented. Indentation will tell Python what needs to be repeated.

Here is an example for a loop that retreives each item in the list, and prints it. The `i` will start from the first index of the list, index `0`, and execute a print command. It will repeat this for all `i` index items in the list. 

list = ['zero', 'one', 'two', 'three', 'four']

for i in list:
    print(i)

The loop will retreive the objects from a list and does something with them. This also works with other data types such as integers and floats.

Range Function

A range function is one of the standard built-in function which counts from 0 up to a certain number. You can add a `range()` function to tell python to loop an `n` number of times. This will output the number of the `i` index. 

for i in range(5):
    print(i)

Output: 

0
1
2
3
4

Instructing Where the Loop to Start

You can also have the loop skip the first index (0). Consider the code below:

for i in range (3):
    print(i+1) # by default the range starts from 0, so we add 1 to the output
print('GO!') # notice that the print statement is outside the for-loop. What will happen if it was inside the loop?

Output:

1
2
3
GO!

Using the range function can have multiple arguments to specify on what number to start, at what number to end, and how many steps. <br> `range(x, y, z)` where x is starting position, y is ending position, and z is the step.

for i in range(5,26,10):
  print(i)

Output:

for i in range(5,26,10):
  print(i)

You can use the `end=` argument to specify how the loop ends after executing the `print()`. For example, we can specify that each iteration of the loop to end with a space instead of entering a new line by adding the argument `end=’ ‘` in the `print()` function. This removes the default value to enter a new line after the print statement.

for i in range(5,0,-1):
    print(i, end=' ')
print('Blast off!!')

Output:

5 4 3 2 1 Blast off!!

Modify a List Using Loops

Examine the sequence of operations and how the list is getting incrementally updated
Examine the sequence of operations and how the list is getting incrementally updated

You can modify the variable in the loop so that the value is incrementally updated. This is a very important concept to get familiar with.

Use the python tutor to see how the program executes this: https://pythontutor.com/render.html#mode=edit

a = 0

for i in range(10):
    a+=3
    print(i, ": ", a)
print("a =", a)

Output:

a = 0
print('a =',a)

for i in range(10):
  a += 3 # a shorter way to write a = a + 3
  print(i, ":  ", a)


# print("10:  ", a)
print("a =" , a)

Small footnote: a+=3 is the same as a = a + 3

Append Items to a List

You can add items to a list using the `.append()` function. This is an essential function for lists. “App-ending” means in this case to add a value at the end of the list. This operation repeats for every iteration in the loop!

my_list = [] # first you must declare a list variable. It can be an empty list or a list with initial values. 

for i in range(3):
  my_list.append(i)
  print(my_list) # because the print statement is inside the loop, it will print the list after each iteration

print("the list contains the following values:", my_list)

Output:

[0]
[0, 1]
[0, 1, 2]
the list contains the following values: [0, 1, 2]

 

Variable Swapping within a Loop

Using variable swapping can make writing code cleaner. Examine the example below:

a = 2
b = 10

for i in range(5):
    a, b = b, a + b
    print("iteration", i+1, "|", "a:", a, "b:", b)

This is conceptually similar to how you write a loop to generate fibonnaci sequence. A fibonnaci sequence is the sum of the last two numbers in the list: 1,1,2,3,5,8,13,21,34,55,89, …

See example below: 

fib_num = [0, 1] # initialize the first two values

for i in range(13):
    next_value = fib_num[-1] + fib_num[-2] # calculate the next fibonacci value 
    # the [-1] and [-2] are used to access the last two elements of the list
    fib_num.append(next_value) # adds it to the fib_num list

print(fib_num)

Output:

[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377]

 

Combining Loops and Conditionals

Suppose you want to create an odd number generator using conditional statements inside a loop. Consider the example below:

x = [] # initialize an empty list

for i in range(10):
  if i % 2 != 0:
    x.append(i)
    print(x, f'the value [{i}] was added to the list', end='\n')

print(f'after looping 10 times, here is the list of values: {x}')

 

Consider this other example that uses a loop to determine the value of numbers:

What does this code do?

odd_vals = []
even_vals = []

for i in range(20):
  if i % 2 == 0:
    even_vals.append(i)
  else:
    odd_vals.append(i)

print("Odd values:", odd_vals)
print("Even values:", even_vals)

And what does this code do?

a = range(1, 12) 

for i in a:
  if i % 10 == 0:
    print(i, ": divisible by 10")
  elif i % 5 == 0:
    print(i, ": not divisible by 10, but divisible by 5")
  elif i % 3 == 0:
    print(i, ": not divisible by 10 or 5, but divisible by 3")
  else:
    print(i, ": not divisible by 10, 5, or 3")

Nested For-Loops

Nested for loops in Python involve placing one for loop inside another. This allows you to iterate over multiple sequences or dimensions. The inner loop runs entirely for each iteration of the outer loop. Nested for loops are commonly used for tasks like processing multi-dimensional arrays, handling nested lists, or performing complex iterations that depend on multiple variables. They provide powerful means to handle more complex data structures and logic.

 

Examples of applications:

Handling images (2D pixel arrays), point grids, tabular data (analysis), matrix operations.

Examine this code. The an index (i) from the list `x` is looped (j) times using range(3). Carefully look at the secuency of operation.

From the inside-out, j loops 3 times of 1 item from the list `x`, then prints a line separator
From the inside-out, j loops 3 times of 1 item from the list `x`, then prints a line separator
x = ['a', 'b', 'c']

for i in x:
  for j in range(3):
    print("i=",i, ", j=",  j)
  print('-----------')

Output:

"""
Nested for loops. 
Use https://pythontutor.com/python-compiler.html#mode=edit to visualize the nested for-loops step by step.
"""

x = ['a', 'b', 'c']

for i in x:
  for j in range(3):
    print("i=",i, ", j=",  j)
  print('-----------')

Enumerate

Enumerate 

Nested loops can create a grid very easily, such as a multiplication table. Examine the code below:

rows = 5
columns = 5

for i in range(1, rows + 1):
    for j in range(1, columns + 1):
        print(f"{i * j:2}", end=" ")  # Print each value in a grid format
    print()  # Move to the next row

Output:

 1  2  3  4  5 
 2  4  6  8 10 
 3  6  9 12 15 
 4  8 12 16 20 
 5 10 15 20 25

Your might encounter this format to consistently space a 2D-grid with the `'{:3d}’.format()` arugment within the print statement:

for i in range(1,11):
    for j in range(1,11):
        print('{:3d}'.format(i*j), end='') 
    print()
# See also 10.7 string formatting in the reading "A Practical Introduction to Python Programming"

 

Examine this example below for a prime number generator:

prime_num = []

for i in range(1, 10):
    is_prime = True  
    for j in range(2, i):
        if i % j == 0:
            is_prime = False
            break 
    if is_prime:
        prime_num.append(i)

print("Prime numbers:", prime_num)

Enumerate

In Python, enumerate is a built-in function that adds a counter to an iterable, such as a list, tuple, or string, and returns it as an enumerate object. This object can be used in loops to obtain both the index and the value of each item in the iterable simultaneously. enumerate is often used to improve code readability and efficiency by eliminating the need for manual counter handling. It accepts two arguments: the iterable to be enumerated and an optional start value to specify the initial index. This function is particularly useful in scenarios where both item positions and their values are required.

L = ['a', 'b', 'c', 'd']
x = []

for (i, value) in enumerate(L):
    print('Index:', i, '|', 'Value:', value)
    x.append((i, value))
    
print(x)
print(list(enumerate(L)))

Output:

Index: 0 | Value: a
Index: 1 | Value: b
Index: 2 | Value: c
Index: 3 | Value: d
[(0, 'a'), (1, 'b'), (2, 'c'), (3, 'd')]
[(0, 'a'), (1, 'b'), (2, 'c'), (3, 'd')]

While-Loops

In Python, a while loop repeatedly executes a block of code as long as a specified condition remains true. It checks the condition before each iteration and continues looping until the condition evaluates to false. This type of loop is useful for scenarios where the number of iterations is not known beforehand and depends on dynamic conditions. The while loop can be controlled using break to exit the loop prematurely or continue to skip to the next iteration.

Tip: Properly managing the loop condition is crucial to avoid infinite loops. Infinite loops may cause software to crash!

a = 0

while a < 5:
  a = a + 1
  print(a)

Output:

1
2
3
4
5

Break and Continue

With the break statement we can stop the loop even if the while condition is true. Check the execution line-by-line on https://pythontutor.com/

i = 1
while i < 6:
  print(i)
  if i == 3:
    break
  i = i + 1

Output:

1
2
3

With the continue statement we can skip an iteration if a condition is met. I.e., if i equals to 3, then it skips the loop remaining executions in the loop. This example below skips the print statement when i equals to 3:

i = 0
while i < 6:
  i = i + 1
  if i == 3:
    continue # if i is 3, it will skip the print statement 
  print(i)

Output:

1
2
4
5
6

Workshop 2: Loop and Conditional Statements 4/6

Useful Resourceslink copied

Recommended Pythin Learning Resources:

Comprehensive Python Tutorials:

Test Your Knowledge:

Helpful Short Educational Videos:

 

Workshop 2: Loop and Conditional Statements 5/6

Conclusion / Next Workshoplink copied

Take the opportunity to experiment with different techniques and adopt a problem-solving attitude. By exploring various methods, you’ll deepen your understanding and discover the most effective solutions for different scenarios. 

Previous Workshop Pages

Workshop 2: Loop and Conditional Statements 6/6

Required Readings Before Workshop 3link copied