Python exercise#
Hopefully by now you have been able to install Conda, VS Code and set up your shiny new environment. Welcome to the final task of the day.
This notebook guides you through some common functionalities in Python that you will use a lot over this course. You will delve into them more in detail later. For now, try them out!
Part 1: Common datatypes#
Below you will see a cell with code. Hover over this cell and you will see a play button to the left. Clicking this button will run the cell.
When you run a notebook for the first time, you will be asked to select a kernel (environment), make sure to select mude-base
!
This will ensure that you have the required setup to continue the rest of the notebook.
If you still have not set this up, please go back to the instructions here.
# Run this cell first to load any needed packages.
# Note that we also create a 'nickname' for the package when importing. This makes it easier for us to refer to the package later in the notebook.
import numpy as np
\(\text{Task 1:}\)
Inspect the code below and take note of the four common datatypes. You should be familiar with these.
Python can automatically tell which is which, but it is a good exercise for you to check as well. You can check this by using the type()
function.
Try finding out what data type each of the variables defined below is by using type()
, the first example is filled out for you.
# Number of floors in a building
num_floors = 5
type_num_floors = type(num_floors)
# Length of column in building
column_length = 3.75
type_column_length = type(column_length)
# String: Type of material
material = "Concrete"
type_material = type(material)
# Boolean: Is the building under maintenance?
building_under_maintenance = True
type_building_under_maintenance = type(building_under_maintenance)
# Print statements
print("Floors:", num_floors, "Data type:", type_num_floors)
print("Column Length:", column_length, "m", "Data type:", type_column_length)
print("Material:", material, "Data type:", type_material)
print("Building Maintenance:", building_under_maintenance, "Data type:", type_building_under_maintenance)
Floors: 5 Data type: <class 'int'>
Column Length: 3.75 m Data type: <class 'float'>
Material: Concrete Data type: <class 'str'>
Building Maintenance: True Data type: <class 'bool'>
\(\text{Solution:}\)
You should have found the following:
num_floors
is an integer numbercolumn_length
is a float. If you have never done any programming before, you will know this as a rational number.material
is a string. A string is any piece of text (or numbers that you want the computer to treat like text).building_under_maintenance
is a boolean. Boolean take only two values, i.e., yes and no, 1 and 0, True or False etc..
End of solution.
Part 2: Variables, Constants, Operators, and Expressions#
Above you have already seen the use of variables to store bits of information. In this next part, you will create your own variable and use it to apply a safety factor to the load in a beam.
Run the cell below to calculate the final load. Observe how we define a value for the beam length and load per meter, and then multiply them together to get the total load.
# Variables
beam_length = 6 # in meters
load_per_meter = 2.5 # in kN/m
# Expression: Total load on the beam
total_load = beam_length * load_per_meter # in kN
print("Total Load on Beam:", total_load, "kN")
Total Load on Beam: 15.0 kN
\(\text{Task 2:}\)
Add a new variable called safety_factor
. Set the safety factor as 1.15 (this is the safety factor of the load).
Then, create a new expression that multiplies the previously calculated total load with the safety factor.
Add the correct variable to print out in the print statement.
# Please assign the correct contents to the variables below.
safety_factor = 1.15
design_load = total_load * safety_factor
# Fill in the print statement below
print("The safety factor is:", safety_factor, "The design load is:", total_load)
The safety factor is: 1.15 The design load is: 15.0
Part 3: Data structures#
Another thing you will run into time and time again in Python are different types of data structures, i.e., how data is organised into a … structure. Python carries a lot of different data structures, but three common ones are shown below. Although the may seem arbitrary at first, different data structures can be manipulated in different ways, meaning you can and should choose the structure that makes the most sense for your needs.
You will learn more about the different data structures as the course goes on. For now, you can warm up with some simple exercises on the use of data structures. These are not a comprehensive manual on how to use each data structure, but aims to show you some of their features.
They are often denoted by the type of bracket surrounding them. Note how this is the case for each of the data structures shown below.
# List: Heights of buildings on a street
building_heights = [10, 15, 20, 25]
# Array: Coordinates of a survey point (x, y)
survey_point = (120.5, 45.8)
# Dictionary: Material strengths (MPa)
material_strengths = {
"Concrete": 30,
"Steel": 250,
"Timber": 12
}
print("Building Heights:", building_heights)
print("Survey Point:", survey_point)
print("Material Strengths:", material_strengths)
Building Heights: [10, 15, 20, 25]
Survey Point: (120.5, 45.8)
Material Strengths: {'Concrete': 30, 'Steel': 250, 'Timber': 12}
Lists
Each entry in a list can be ‘retrieved’ through that entry’s index in the list. Note that in Python, we start counting from zero! This means, if you want to find the second entry in the list, you will have to ask Python for the entry with index 1. One syntax for accessing an entry of a certain index in a list is entry = list_name[index]
Tuples
Tuples function much like a list. However, elements cannot be added or removed once the tuple is created. The indexing works the same way as with lists.
Dictionaries
Dictionaries allow us to store sets of values and keys. In the example above, each key, i.e., each material, has an associated value, i.e., their strengths. If we want to retrieve a value in a dictionary, we need to use the key, rather than the index, as was the case with lists. This means the syntax will be entry = dictionary_name[key_name]
\(\text{Task 3:}\) This task will ask you to do an operation on each of the data types shown above.
Retrieve the last entry in the list and print it out. Remember the starting index in Python is zero.
Retrieve the 1st entry in the tuple and print it out.
From the dictionary, please retrieve the strength for steel. Remember that the keys are strings.
# List
last_entry_list = building_heights[3]
# Tuple
first_entry_tuple = survey_point[0]
# Dictionary
steel_strength = material_strengths['Steel']
print('Last entry in list:', last_entry_list)
print('Steel strength:', steel_strength, 'MPa')
Last entry in list: 25
Steel strength: 250 MPa
Part 4: Conditional statements#
Another core functionality of Python, or any other programming language, is the use of conditional statements. These act as a flowchart through your code, activating certain parts if the given conditions are (or aren’t) met. Study the code below and try to predict which branch gets activated. You can run the cell to check.
load_capacity = 50 # in tons
total_load = 48 # in tons
# Conditional statements
if total_load < load_capacity:
print("Safe to proceed.")
elif total_load == load_capacity:
print("At maximum capacity.")
else:
print("Overloaded! Reduce the load.")
Safe to proceed.
But wait! Earlier we defined a safety factor for our load and we want to use this to compare against our load capacity. Let us do that in the task below.
\(\text{Task 4:}\)
Edit the code above so that you can calculate the design load by multiplying the total load with the load safety factor of 1.15. Then, change the conditional statements so that they compare the load capacity against the design load. Are we able to proceed?
load_capacity = 50 # in tons
total_load = 48 # in tons
design_load = total_load * 1.15
# Conditional statements
if design_load < load_capacity:
print("Safe to proceed.")
elif design_load == load_capacity:
print("At maximum capacity.")
else:
print("Overloaded! Reduce the load.")
Overloaded! Reduce the load.
\(\text{Solution:}\)
You will find that, once the safety factor is applied, our design load is actually 55.2 kN. Your printout should be “Overloaded! Reduce the load.”
End of solution.
Part 5: Loops#
We often want to do the same operation on a series of values. As you probably can tell, this quickly becomes extremely tedious and inefficient as your list of values get longer. Loops are a great way to iterate through a series of values using the same set of operations.
To create a loop you fundamentally need two things: The first is a set of values you want to iterate through. The second is the loop itself. In the example below, there is a list with three different beam lengths. This will act as our set of values to iterate through. Next, there is the loop itself. The first line defines the ‘running scope’ of the loop, i.e., for what set of values you are running the loop for. The syntax in this case is for x in y
. In this case, each x
is called a length
and the y
we iterate through is beam_lengths
.
Inside this loop, the operations then take place. In the first iteration, the loop takes the first entry in the list, 4, and uses this value to calculate the total load. In the next iteration, the loop will take the next entry in the list, 5 and so on.
A note on equal signs
One thing to note is that the equals sign here works a bit differently than an equals sign in maths. Instead of saying that A is the same as B, the equals sign assigns A to B. In the first task, you can see that beam_length = 6
. In this case, we take the integer 6 and assign it to beam_length
. This means that if we want to assign a value of 7 to beam_length
, we can simply type beam_length = 7
. Because the value is being assigned to beam_length
, we won’t have any issues with the fact that 6 is not equal to 7. When you assign a value, you override the previous value.
The same thing happens in the loop below. For each time the loop runs, a new value is assigned to total_length
and . The value is then printed out. In the next loop, the old value is overwritten by the new value.
# List of beam lengths to calculate total load for each
beam_lengths = [4, 5, 6] #m
load_per_meter = 2.5 # kN/m
for length in beam_lengths:
total_load = length * load_per_meter
print(f"Beam Length: {length}m -> Load: {total_load} kN")
Beam Length: 4m -> Load: 10.0 kN
Beam Length: 5m -> Load: 12.5 kN
Beam Length: 6m -> Load: 15.0 kN
\(\text{Task 5:}\)
Apply the safety factor again so that we use a design load instead of the total load. Do this is two different ways:
By editing the input values, i.e., things outside the loop.
By editing the loop itself.
You should have two separate solutions, one for each case. You may also want to rename total_load
to design_load
for propriety.
# Input values
beam_lengths = [4, 5, 6]
load_per_meter = 2.5 * 1.15 # kN/m
for length in beam_lengths:
design_load = length * load_per_meter
print(f"Beam Length: {length}m -> Load: {design_load} kN")
# Loop
beam_lengths = [4, 5, 6]
load_per_meter = 2.5
for length in beam_lengths:
design_load = length * load_per_meter * 1.15
print(f"Beam Length: {length}m -> Load: {design_load} kN")
Beam Length: 4m -> Load: 11.5 kN
Beam Length: 5m -> Load: 14.375 kN
Beam Length: 6m -> Load: 17.25 kN
Beam Length: 4m -> Load: 11.5 kN
Beam Length: 5m -> Load: 14.374999999999998 kN
Beam Length: 6m -> Load: 17.25 kN
Well done on completing your first notebook in MUDE! We know this may be a lot to take in, but with regular use we are sure you will get comfortable with Python soon enough.
End of notebook
By Jialei Ding, Delft University of Technology. CC BY 4.0, more info on the Credits page of Workbook.