Skip to content

Assignmants

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)