2. Programming language

Functions

More complex computer programs usually contain a number of “subroutines”, which are referred to as “procedures”, “methods” or “functions” in programming. The purpose of a function is to perform a specific “subtask” in the program that is used repeatedly by the main program. This also serves to make the program clearer and reduce program errors.

For example, imagine a geologist examining earthquake data and having to repeatedly perform some calculations - e.g. determining the average magnitude of earthquakes or selecting data for only the strongest earthquakes. Instead of doing the work from scratch each time, he can create functions for each task and use them as needed. Here is an example of a function called “average_magnitude”:

  • In Python, a function is defined with the keyword def.
  • In the example, the function is called “average_magnitude”.
  • The function has two “inputs” or parameters, called “magnitude1” and “magnitude2”, which represent the magnitudes of two earthquakes.
  • Within the function, the two magnitudes are added together, divided by 2 to find the average, and then this result is returned to us. This final result is called the return value.
  • average_magnitude(magnitude1, magnitude2) is a function call. This calls the function average_magnitude and provides it with two values, namely the earthquake magnitudes magnitude1 and magnitude2.
  • When called, the function takes the received values, calculates the average and returns the result.
  • The returned result (the average) is then stored in the variable “average”.

Other examples of the use of functions are:

  • Video game: When a character uses an ability to attack a monster, the function checks the strength of the character and the monster and updates the monster's health accordingly.
  • Course management: A function can be defined to combine a student's previous exam and project grades to determine the final grade.
  • Spam email detection: A function can be defined to check whether an email contains spam-suspicious words and malicious links. Such a function is called every time the user receives a new e-mail.
 

 

EXERCISES

We want to support your learning process by involving you in five different activities. Each activity represents a step in building your programming skills, with the tasks becoming progressively more detailed and sophisticated. You are welcome to try again if you don't get it right first time, but please try hard enough before moving on to our suggested solutions.
 

A geologist researching earthquakes needs a program to classify earthquake magnitudes using the Richter scale and to suggest safety measures. Your task is to create functions that help the geologist to quickly classify earthquakes and provide guidance even in remote areas.

Could you help him by completing the following tasks?

 
 
 EXERCISE 1

 

The geologist has developed a function for classifying the strength of earthquakes.

Now follow the code and answer the questions. Score 100% of the points in the following quiz. You are welcome to try again if you do not succeed.

 
 
 

Based on the classification under https://www.britannica.com/science/Richter-scale 

 

 EXERCISE 2
 

Next, the geologist wants to classify the magnitudes of various earthquakes and print them out on the screen.

Run the program below, analyze it, submit it and receive a congratulatory message.

 
 
 
Instructions Analyze the following code and use it to submit and receive the congratulatory message. 
def classify_magnitude(richter_skala):
    if richter_skala < 3.0:
        return "Micro"
    elif 3.0 <= richter_skala < 4.0:
        return "Low"
    elif 4.0 <= richter_skala < 5.0:
        return "Slight"
    elif 5.0 <= richter_skala < 6.0:
        return "Moderate"
    elif 6.0 <= richter_skala < 7.0:
        return "Strong"
    elif 7.0 <= richter_skala < 8.0:
        return "Severe"
    else:
        return "Very Severe"
    
print(classify_magnitude(2.5))   
print(classify_magnitude(3.5))  
print(classify_magnitude(4.7))   
print(classify_magnitude(6.5))   
print(classify_magnitude(8.5))  
 

2. Possible solution
def classify_magnitude(richter_skala):
    if richter_skala < 3.0:
        return "Micro"
    elif 3.0 <= richter_skala < 4.0:
        return "Low"
    elif 4.0 <= richter_skala < 5.0:
        return "Slight"
    elif 5.0 <= richter_skala < 6.0:
        return "Moderate"
    elif 6.0 <= richter_skala < 7.0:
        return "Strong"
    elif 7.0 <= richter_skala < 8.0:
        return "Severe"
    else:
        return "Very Severe"

print(classify_magnitude(2.5))
print(classify_magnitude(3.5))
print(classify_magnitude(4.7))
print(classify_magnitude(6.5))
print(classify_magnitude(8.5))
    
 
 
 EXERCISE 3
 

Examine the previous code and answer the following questions.

Solve the following quiz and achieve a score of 100%. If you answer some questions incorrectly, you are welcome to try again.

 
 

 
 EXERCISE 4
 

The geologist would like to add recommendations for each classification to his earthquake analysis. This will help him to give clear recommendations for action to local authorities based on the severity of an earthquake. Your task is to write a new function called “recommend_action” that provides a recommended action based on the classification of “classify_magnitude”.

Read the instructions and modify the code below. Submit it to receive a congratulatory message.


Instructions
 

Step 1:

  • Create a new function with the name “recommend_action”.
  • This function should contain a parameter: classification, which represents the earthquake classification (e.g. “Micro”, “Low”, “Light”).

Step 2:

  • Use if and elif statements to specify conditions for each earthquake classification.
  • For each classification level, specify a specific recommended measure as the return value of the function.
    • For “Micro”: “No measures required.”
    • For “Low”: “Issue warnings, no further measures.”
    • For “Slight”: “Check safety of surroundings.”
    • For “Moderate”: “Notify emergency services and check safety precautions.”
    • For “Strong”: “Take precautions in populated areas.”
    • For “Severe”: “Consider evacuation in affected areas.”
    • For “Very Severe”: “Evacuation and immediate emergency measures.”

Example:

if classification == "Micro":
        return "No measures required."
...

Step 3:

  • Send in the program and receive the 'Congratulations'.

4. Possible solution

def recommend_action(classification):
    if classification == "Micro":
        return "No measures required."
    elif classification == "Low":
        return "Issue warnings, no further measures."
    elif classification == "Slight":
        return "Safety check of the environment."
    elif classification == "Moderate":
        return "Notify emergency services and check safety precautions."
    elif classification == "Strong":
        return "Precautionary measures in populated areas."
    elif classification == "Severe":
        return "Consider evacuations in affected areas."
    elif classification == "Very Severe":
        return "Evacuation and immediate emergency measures."

print(recommend_action("Micro"))        
print(recommend_action("Slight"))        
print(recommend_action("Very Severe"))
 
 
 EXERCISE 5 (OPTIONAL)

 

Now that the geologist has both a classification function and an action recommendation function, he wants a function that combines these into a single user-friendly function called “analyze_earthquake”. By creating “analyze_earthquake”, the geologist can now quickly analyze earthquakes by both classifying their magnitude and making recommendations for action, providing valuable insights for the safety of the population.

Run the program by following the instructions below. Send the code to receive the congratulatory message.


Instructions Step 1:
Write a function called analyze_earthquake that takes the magnitude of the Richter scale as input. This function should:
  • classify_magnitude to determine the classification of the earthquake based on its magnitude.
  • recommend_action to provide a recommended action based on the classification.
  • return a message containing both the classification and the recommended action. The function should return a formatted message in German. For example:

„Earthquake classification: Moderate. Recommended action: Notify emergency services and check safety precautions.“


Step 2:
Test analyze_earthquake with different values of the Richter scale to see if the classification and the recommended action are output correctly.
Example test cases:
  • Input: 2.5 - Expected output: “Earthquake classification: Micro. Recommended action: No action required.”
  • Input: 4.5 - Expected output: “Earthquake classification: Light. Recommended action: Safety check of the surroundings.”
  • Input: 6.5 - Expected output: “Earthquake classification: Severe. Recommended action: Consider evacuations in affected areas.”


Step 3:
  • Send the message and receive the congratulatory message.

5. Possible solution
# Already done: Function to classify earthquake magnitude based on the Richter scale
def classify_magnitude(richter_skala):
    if richter_skala < 3.0:
        return "Micro"
    elif 3.0 <= richter_skala < 4.0:
        return "Low"
    elif 4.0 <= richter_skala < 5.0:
        return "Slight"
    elif 5.0 <= richter_skala < 6.0:
        return "Moderate"
    elif 6.0 <= richter_skala < 7.0:
        return "Strong"
    elif 7.0 <= richter_skala < 8.0:
        return "Severe"
    else:
        return "Very Severe"


# Already done: Function to recommend actions based on the classification
def recommend_action(classification):
    if classification == "Micro":
        return "No measures required."
    elif classification == "Low":
        return "Issue warnings, no further measures."
    elif classification == "Slight":
        return "Safety inspection of the environment."
    elif classification == "Moderate":
        return "Notify emergency services and check safety precautions."
    elif classification == "Strong":
        return "Take precautionary measures in populated areas."
    elif classification == "Severe":
        return "Consider evacuations in affected areas."
    elif classification == "Very Severe":
        return "Evacuation and immediate emergency response required."


# Task: Function to analyze the earthquake, combining classification and recommendations
def analyze_earthquake(richter_skala):
    classification = classify_magnitude(richter_skala)
    action = recommend_action(classification)
    return "Earthquake classification: " + str(classification) + ". Recommended action: " + str(action)


# Test cases: please do not modify
print(analyze_earthquake(2.5))
print(analyze_earthquake(4.5))
print(analyze_earthquake(6.5))
print(analyze_earthquake(8.5))
    
 
 
!    

 Message to take away

We have learned how to define functions that receive data via parameters and return a value to the program. Functions are particularly useful for tasks that need to be reused multiple times within a program. They make programming easier by breaking down larger problems into smaller, more manageable parts.