# 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¶

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.

### 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.

#### Example: Assigning a Fixed Value¶

diameter = 5


#### Example: Assigning 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: Assigning the Result of a Function Call¶

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

whole_number = round(4.7)


#### Example: Mixing Function Calls and Calculations¶

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 Definitions¶

#### Use Case¶

Extract code into a separate segment to reduce complexity, and allow for re-usability.

Functions are separate sections of code that can be executed at will. They have parameters that describe the input values into a function and are used to control a functions’ inner workings. Further, functions may generate an output value that can be returned to indicate for example a calculation result.

A function definition only declares which parameters and return values there are and what code will be executed. To actually run the code inside a function, it needs to be called.

When a function modifies the programs’ state directly (besides returning a value) it is said to have a side effect. Side effects are usually considered bad practise, since they can make programs very confusing and hard to understand and debug. Functions that rely only on their parameters for information input and have no side-effects are called pure functions.

#### Example: Function with no Parameters¶

This is a minimal example of a function that has

Input Parameters Return Value Side effects Pure function
Yes
# Function definition
def say_hello():
print("Hello World")

# Function call
say_hello()  # No variable needed to catch return value


#### Example: Function with Parameters and Return Value¶

This is a more complex function that clamps a value between a minimum and maximum.

Input Parameters Return Value Side effects Pure function
value, clamped value Yes
minimum,
maximum
# Function definition

def clamp(value, minimum, maximum):
if value < minimum:
return minimum
elif value > maximum:
return maximum
else:
return value

# Function call (positional arguments)
clamped_value = clamp(10, 0, 5)  # clamped_value will be 5

# Function call (named arguments)
clamped_value = clamp(minimum=0, maximum=5, value=10)  # clamped_value will be 5


### Function Call¶

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.

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.

#### 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 corresponding argument is named sep. 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


## Imports¶

Importing elements from another Python module makes them available in the current context (usually a script or a REPL-session). This allows for code to be split into several segments to keep them invididually self-contained, reusable and maintainable.

#### Use case¶

Make a separate module or elements of a module available in the current context.

#### Example: Importing a whole Module¶

In the following example, we import the math-module from _Python_s standard library and access the sin(…)-function and pi therein.

import math

print(math.sin(math.pi))


#### Example: Importing Elements from a Module¶

In this example, only the sin(…)-function and pi will be imported and used.

from math import sin, pi

print(sin(pi))


## 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.

Conditions

Conditions are expressed as statements that can be evaluated to be either True or False. For example x > 5, "H" in "Hello World", or isinstance(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("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 to guarantee that we check both, the heater and the cooler. This is the reason why we use two if statements instead of an ifelif combination.

## Loops¶

Loops are generally used to repeat sections of code instead of spelling them out again. In Python, two types of loop are distinguished: the while- and the for-loop. The repetitions within a loop are called iterations.

Loops inside loops

There are cases where loops have to be placed inside other loops. This is called nesting or nested loops. In such cases, these loops get distinguished by talking about inner and outer loops.

In the following example, the for-loop is nested inside the while-loop.

while not food_is_spicy:
for spice in [salt, pepper, chilli]:
throw_in_pot(spice)
food_is_spicy = taste_food()

Here, the for-loop would be considered the inner loop, which gets executed completely for each iteration of the outer while-loop. Nesting loops tends to increase the complexity of a program considerably, making it harder to read, understand and maintain. To counteract this, a common strategy is to extract the inner loops into their own functions so they can be handled separately.

### while-Loops¶

As long as a condition is fulfilled, repeat a section of code.

#### Use Case¶

Looping over code when it is not initially clear, how many iterations will be required or when a condition will change.

Request the user to input the word “exit”. Repeat the request until the correct input is made.

user_input = None

while not user_input == "exit":
user_input = input("Please type the word \"exit\": ")


Note that the variable user_input needs to exist before the loop, so it can be compared in the beginning of the loop.

### for-Loops¶

Go over each element of a given collection of data.

#### Use Case¶

Looping over code where the amount of iterations is predictable.

Data sources for the loop

Anything that is iterable can serve as a data souce in for-loops. This can be (amongst others) Lists, Sets, Tuples, Dictionaries, Ranges, or Strings.

#### Example 1¶

Using a for-loop to print all numbers in a fixed list and their square.

for number in [2, 3, 5, 7, 11, 13]:
print(number, number ** 2)


### The break Keyword¶

This keyword will abort the execution of the loop it is in. The code will resume after the loop as usual. In the case of nested loops, only the loop that the keyword is in will be affected.

The following loop will print a shopping list and stop as soon as the word "end" is reached.

shopping_list = ["potato", "apple", "end", "banana"]

for item in shopping_list:
if item == "end":
break
print(item)


### The continue Keyword¶

This keyword is used inside a loop body. It will trigger the loop to skip the rest of the current iteration and start the next one right away. Note that the keyword only affects the loop it is directly in, not any outer loops.

#### Example 1¶

In the following loop, we sum all values from 0 to 99, but skip each number ending with 3.

total = 0

for number in range(100):
if number % 10 == 3:
print("Skipping number", number)
continue
total = total + number

print("Sum from 0 … 99 (without numbers ending on 3):", total)


#### Example 2¶

List all files in a folder. The continue here is used to skip everything that is not a file (like sub-folders).

from pathlib import Path

folder = Path("/path/to/the/folder")

for entry in folder:
if not entry.is_file():
continue
file_name = entry.name
file_size = entry.stat().st_size
print(f"{file_name}: {file_size} Bytes")