Flow Control

When we embark on the exciting journey of learning to program, we soon discover that programming is not just about writing code, but also about controlling the flow of that code. We can compare it to the flow of decisions we make in our daily lives. For example, if it’s cold outside, we put on a coat before going out. If we have no pending tasks, we go to the movies. Our actions depend on these evaluations and decisions. Control flow is, essentially, the way we decide which part of the code runs, when it runs, and how many times it does. To do this, we have a variety of structures that allow us to make decisions, repeat actions, and split our code into logical blocks.

Conditions: making decisions in code

Life is full of decisions: “If it rains, I’ll take an umbrella. Otherwise, I’ll wear sunglasses.” These decisions are also present in the world of programming. Conditions are like questions the computer asks itself. They allow us to make decisions and execute specific code based on a condition1. They can be as simple as “Is it raining?” or as complex as “Is it the weekend and do I have less than $100 in my bank account?”.

if

The if structure allows us to evaluate conditions and make decisions based on the result of that evaluation.

1age = 15
2
3if age >= 18:
4    print("You are an adult")

The code above allows executing a portion of code if a person’s age is greater than or equal to 18 years.

if-else

When you want to execute alternative code if the condition is false, you use the if-else structure.

1age = 21
2if age >= 18:
3    print("You are an adult")
4else:
5    print("You are a minor")

In this case, it determines if the person is an adult or a minor, and the message displayed is different.

if-elif-else

When conditions are multiple and two paths are not enough, the if-elif-else structure is used to evaluate them in a chained way.

1age = 5
2if age <= 13:
3    print("You are a child")
4elif age > 13 and age < 18:
5    print("You are a teenager")
6else:
7    print("You are an adult")

In the code above, there are three clear paths: one for when age is less than or equal to 13, one for when age is between 13 and 18, and another for when age is greater than or equal to 18.

Another way to solve this problem is through the switch-case structure, which, although Python does not natively incorporate, other languages like Java or C++ do, and it is an important tool to be familiar with. This structure allows programmers to handle multiple conditions in a more organized way than a series of if-elif-else.

In Java, for example:

 1int day = 3;
 2switch(day) {
 3  case 1:
 4    System.out.println("Monday");
 5    break;
 6  case 2:
 7    System.out.println("Tuesday");
 8    break;
 9  case 3:
10    System.out.println("Wednesday");
11    break;
12  // ... and so on
13  default:
14    System.out.println("Invalid day");
15}

In the previous example, depending on the value of day, the corresponding day will be printed2.


Loops: repeating actions

Sometimes in programming we need to repeat an action several times. Instead of writing the same code many times, we can use loops. These allow repeating the execution of a block of code while a condition is met3.

while

The while loop is useful when we want to repeat an action based on a condition.

1# Prints 1 to 5
2i = 1
3while i <= 5:
4    print(i)
5    i = i + 1

do-while

Similar to while but guarantees at least one execution since the code block is executed first and then the condition is evaluated. Python does not implement this structure, but other languages like Java and C++ do.

1int i = 1;
2
3do {
4  System.out.println(i);
5  i++;
6} while(i <= 5);
1int number = 0;
2do {
3  std::cout << "Hello, world!" << std::endl;
4  number++;
5} while (number < 5);

for

The for loop is useful when we know how many times we want to repeat an action.

1for i in range(5):
2    print("Hello, world!")

The code above will print “Hello, world!” five times.

We can also iterate over the elements of a list or iterable object:

1names = ["Maria", "Florencia", "Julian"]
2for name in names:
3    print(f"Hello {name}")
4
5# Prints
6# Hello Maria
7# Hello Florencia
8# Hello Julian

The break and continue statements

We can use break to terminate the loop and continue to skip to the next iteration.

break is used to completely terminate the loop when a condition is met, in the following example, when i reaches 5.

 1# break example
 2i = 0
 3while i < 10:
 4  print(i)
 5  if i == 5:
 6    break
 7  i += 1
 8
 9# Prints:
10# 0
11# 1
12# 2
13# 3
14# 4
15# 5

continue is used to skip an iteration of the loop and continue with the next one when a condition is met. Here we use it to skip even numbers.

 1# continue example
 2i = 0
 3while i < 10:
 4  i += 1
 5  if i % 2 == 0:
 6    continue
 7  print(i)
 8
 9# Prints:
10# 1
11# 3
12# 5
13# 7
14# 9

Nesting: combining structures

Control flow structures can be nested within each other. For example, we can have loops within loops or conditions within loops.

1for i in range(5):
2  for j in range(10):
3    if (i % 2 == 0 and j % 3 == 0):
4      print(f"i = {i}, j = {j}")

This code will print combinations of i and j only when i is divisible by 2 and j is divisible by 3, demonstrating how loops are nested and executed3.


Common usage patterns

There are specific patterns to solve common needs with control flow.

Search for a value in a collection:

 1fruits = ["apple", "orange"]
 2
 3searching = "orange"
 4found = False
 5
 6for fruit in fruits:
 7    if fruit == searching:
 8        found = True
 9        break
10
11if found:
12    print("Fruit found!")

Accumulation

Accumulate incremental values in a loop:

1total = 0
2
3for i in range(10):
4    total += i
5
6print(total) # Sum from 0..9 = 45

Flowcharts: the visual route to understanding code

Programmers, whether beginners or experts, often find themselves facing challenges that require detailed planning before diving into code. This is where flowcharts come into play as an essential tool. These charts are graphical representations of the processes and logic behind a program or system. In this article, we will unravel the world of flowcharts, from basic concepts to advanced techniques, and how they can benefit programmers of all levels.

A flowchart is a graphical representation of a process. It uses specific symbols to represent different types of instructions or actions. Its main purpose is to simplify understanding of a process by showing step by step how information or decisions flow. These charts:

  • Facilitate understanding of complex processes.
  • Aid in the design and planning phase of a program.
  • Serve as documentation and reference for future developments.

Flowcharts are a powerful tool that not only benefits beginners but also experienced programmers. They provide a clear and structured view of a process or program, facilitating planning, design, and communication between team members.

Basic elements

Flowcharts consist of several symbols, each with a specific meaning:

  • Oval: Represents the start or end of a process.
  • Rectangle: Denotes an operation or instruction.
  • Diamond: Indicates a decision based on a condition.
  • Arrows: Show the direction of flow.
graph TD;
    start((Start))
    process[Process]
    decision{Decision?}
    final((End))

    start --> process;
    process --> decision;
    decision --> |Yes| process
    decision --> |No| final

Examples

Let’s design a flowchart for a program that asks for a number and tells us if it’s even or odd.

graph TB
    start((Start))
    input[Input number]
    decision{Even?}
    isEven[Is even]
    isOdd[Is odd]
    final((End))

    start --> input
    input --> decision
    decision --> |Yes| isEven
    decision --> |No| isOdd
    isEven --> final
    isOdd --> final

As programs become more complex, you may need to incorporate loops, multiple conditions, and other advanced elements into your flowchart. For example, here we diagram a program that sums numbers from 1 to a number entered by the user.

graph TD
    start((Start))
    input[Input number]
    setVariables[Set sum=0 and counter=1]
    loop_condition{counter <= N?}
    loop_code[Add value and increment counter]
    result[Show sum]
    final((End))

    start --> input
    input --> setVariables
    setVariables --> loop_condition
    loop_condition --> |Yes| loop_code
    loop_code --> loop_condition
    loop_condition --> |No| result
    result --> final

Conclusion

Control flow is the heart of programming. Without it, programs would be linear sequences of actions without the ability to make decisions or repeat tasks. By mastering these structures not only do you improve your ability to write code, but also your ability to think logically and solve complex problems.



References


  1. Lutz, M. (2013). Learning Python: Powerful Object-Oriented Programming. O’Reilly Media, Incorporated. ↩︎

  2. Deitel, P., & Deitel, H. (2012). Java: How to program. Upper Saddle River, NJ: Prentice Hall. ↩︎

  3. Matthes, E. (2015). Python crash course: A hands-on, project-based introduction to programming. San Francisco, CA: No Starch Press. ↩︎ ↩︎