Skip to content

Code Structure Elements

Program code can be subdivided into several elements that fulfill specific purposes. Those described in this document are considered to be the fundamental ones, sufficient to solve any programming problem. Many additional structural elements exist, mostly to enable the programmer to tackle very complex problems more easily and in a more convenient way. Some of these elements come in variations, which usually depend on the use-case they are employed for.

Assignments

Simple Assignment

In a simple assignment a fixed value or the result of a calculation is stored in a variable.

Use case
Make the computer remember a value under a given name to be retrieved later.

The right side comes first

Assignments are considered to have a left side and a right side with the = being the separator between the two. On the left side stands the variable in which the data is to be stored. On the right side stands either the data itself or any kind of structure that results in a piece of data after its evaluation. This requires the right side to be fully evaluated (or calculated) first, before the actual assignment can be completed.

Example 1

Assign fixed value.

diameter = 5

Example 2

Assign the result of a calculation.

circumference = diameter * 3.141

Assignment with Function Call

When a function returns a value (i.e. if it has a “result”) it can be stored in a variable for further computation. This is essentially a variation of the simple assignment where a function call takes the role of a value.

Use case
Remembering the “result” of a function even after the function has been completed.

Example 1

Round the value 4.7 using the round(…)-function and store the result in the variable whole_number.

whole_number = round(4.7)

Example 2

Function calls and calculations may also be mixed. Assuming you have two variables side_a and side_b containing the side lengths of a rectangle and you want to calculate the ratio of these sides.

A ratio is usually given as $ \text{larger side} / \text{smaller side} $. Since we do not exactly know which is which we have to use the calls to min(…) and max(…) first and then divide their results. Last we store the calculated value in the side_ratio variable

side_ratio = max(side_a, side_b) / min(side_a, side_b)

Function Call

Calling a function refers to its usage to execute a functions’ code according to the function definition.

Use case
Employ a previously defined function to complete a more complex task.

A function may require additional information to complete its task. When calling a function, these are referred to as arguments. Some arguments are required, others may be optional or use a default value instead.

Don’t forget the parenthesis

To call a function you write down its name followed by parenthesis ( and ). If there are arguments for the function they are specified between the parenthesis. But even if there are no arguments, the parenthesis must be there.

Example 1

Call the function print(…) without any arguments You still need the parenthesis () even if they are empty!

print()

Example 2

Call the function print(…) with one argument.

print("Hello World")

Example 3

Call the function print(…) with many arguments. Multiple arguments are separated by a comma.

print("Hello", "World", "how", "are", "you?")

Example 4

You can also use variables as arguments.

my_text = "Hello World"
print(my_text)

Example 5

Arguments have names and may be referenced by them. Here we use -- as the word separator. The names and meanings of the possible argument names are defined by the function definition. You may want to check the functions’ documentation for details.

print("Hello", "World", sep="--")

Output:

Hello--World

Conditional

Based on a given condition, decide which actions are to be taken.

Use case
Handle diverging paths of action based on the current state of the program.

//// info | Conditions

Conditions are expressed as statements that can be evaluated to be either True or False. For example x > 5, "H" in "Hello World", orisinstance(5, int)`

////

Conditionals are made up of three main components, called branches. If any of these branches has a condition that is met, the code belonging to the branch will be run. Code that belongs to a branch is identified by directly following the conditional and being indented one level (4 spaces) relative to the conditional.

There can only be one

The conditions of the branches are checked in the order they appear. The first branch that will be chosen, completes the conditional. All other branches are then ignored. When writing a conditional, check the special cases first and the general ones later.

if-branch: * Starts a new conditional * Has a condition and will be taken if the condition is met

elif-branch: * Optional, following an if or another elif-branch * Has a condition and will be taken if the condition is met

else-branch: * Optional, but always the last branch * Has no condition and will always be taken if reached * Used to specify the “last ressort”-cases

Example 1

A simple check if the condition x > 1000 is met. Should this is the case, print the text x is a large number

if x > 1000:
    print("x is a large number")

Example 2

Check whether the term "Hello" is contained in the variable my_text. Depending on whether this is the case, a text will be printed accordingly.

if "Hello" in my_text:
    print("Your text contains the word \"Hello\"")
else:
    print(print("Your text does not contain the word \"Hello\""))

Example 3

Check multiple conditions one after the other to decide on a course of action. Within each branch, arbitray complex code may be executed.

This example deals with the heat regulation of bath water. We assume to have a heater and a cooler for the water and want to keep it in the range 25…35°C. To control the devices we may have the set_heater_on(…) and set_cooler_on(…) to toggle these components on and off. The variables heater_is_on, cooler_is_on and temperature inform us about the state of our system.

if temperature > 35:
    print("Water is too hot, will lower the temperature")
    set_heater_on(True)
elif temperature < 25:
    print("Water is too cold, will raise temperature")
    set_cooler_on(True)
else:
    print("Water temperature is acceptable for humans")
    if heater_is_on:
        set_heater_on(False)
    if cooler_is_on:
        set_cooler_on(False)

Note that the checks made in the else-branch are independent of each other. This is the reason why we use two if statements instead of an ifelif combination.

while-loops

for-loops

Function Definitions

Imports