2. Programming languages

Conditional statement


 

Professionals are constantly making decisions in their working lives. For example:

  • Professors decide whether students have passed based on their attendance and grades.
  • Economists use inflation and employment data to decide what advice to give on investment strategies.
  • Company managers use sales data and market trends to decide on product launches or marketing campaigns.
  • Psychologists rely on assessments to decide which treatments to recommend.
In programming, we can create programs that make decisions using so-called conditional statements. Conditions help a program to choose between different actions based on certain conditions that we define. We often use„If“-statements.
 

For example, if a biologist wants to create a program that can determine water quality based on pH, the biologist could use conditions. See the following example:

In Python and Blockly a conditional statement checks whether something is true or false and then decides based on that, what is to be done. This is how it works:

  • The code checks whether pH_level is exactly 7.
    • If this is true, water_quality is set to “neutral”.
    • If this is incorrect, further checks will be carried out:
      • If pH_level is less than 7, water_quality becomes “acidic”.
      • If the pH value is greater than 7, the water quality becomes “alkaline”.

The key word if introduces a condition. elif adds another condition, when the condition before was false. The else-statement is executed, when the previous conditions are not met. We have the comparison operator „==“,

 

Comparison operators

Comparison operators evaluate an expression as a Boolean value. The following table contains the most basic comparison operators and their examples.

 
Syntax(Symbol) Name Description Example
== is equal Returns “True” if both sides are equal.  5 == 5 returns „True“.
!=

is unequal

Returns „Ture“, when both sides are different from eachother. 5 != „5“ returns „True“.
> is greater than Returns “True” if the left side is greater. 3,0 > 3 returns „False“.
< is less than  Returns “True” if the left side is smaller.  2,9 < 3 returns „True“.
 

The Boolean expressions formed with comparison operators must be passed to an if-else statement. See the following example:

if 5 != 7:
    print("Results are not equal")
else:
    print("Results are equal")

The code above outputs “Results are not equal”, as 5 != 7 returns the value “True”. There are a few points to note here: 

1. The lines after a colon “:” must be indented. Although various indentation schemes can be used, it is usual to indicate an indent by a tab or four spaces. Please choose a uniform method!
 
2. Several lines can be specified at once in an if, elif or else statement, as long as they are all indented correctly.
3. the else statement can be omitted. If the condition in the if statement is “false”, the program simply continues with the next line without doing anything. But remember that an else statement only works if there is an if statement before it.
 
 

 

The result of pH_level == 7 is a boolean value - either “True” or “False”. If it is “True” (the pH value is 7), “water_quality” is set to “neutral”. If it is “False” (the pH value is not 7), the program jumps to the elif- or else-part.

Boolean values

The conditions must first be evaluated to obtain boolean data types (true or false) so that the program can be routed to separate branches. A boolean variable is a variable that can only have two values: true or false. These values are described as boolean values, and the variable also has a Boolean data type. Here are some examples of Boolean variables.

    • student_pass: This variable has the value “True” if the student has passed and “False” if the student has failed.
    • onclick: This variable has the value “True” if the user clicks on a specific object on a web page and “False” if they do not click on it.
    • check_integrity: This variable has the value “True” if a file is classified as intact when checked by a program, and “False” if the program determines that the file is damaged.

Just for Fun: In many programming languages, the number 0 is interpreted as false and any other number as true. Considering that computers are actually made up of zeros and ones, this is perhaps a logical result.

 


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 tasks becoming progressively more detailed and sophisticated. 
 
You are welcome to try again if you didn't get it right the first time, but please try hard enough before turning to our suggested solutions.
 

A biologist is passionate about protecting her favorite bird species, which is threatened by the loss of its habitat. In order to make informed decisions about the necessary conservation measures, she collects data on the population density of this species in different habitats. The population density is calculated by dividing the number of birds by the size of the area. In this way, she hopes to be able to decide which areas need the most conservation support.

Can you help her by completing the following tasks?

 
 
  EXERCISE 1
!

The biologist has developed a program that, when it receives data on the population density of the bird species in a particular habitat, automatically determines the priority of the habitat for conservation measures.

Now follow the code and answer the questions. Achieve 100% of the points in the following quiz. You can try again if you have done something wrong.

The variable “bird population density” shows the number of birds per unit area.

EXERCISE 2
!    

It decided to establish other criteria. If the population density of the bird species is now between 1000 and 300, it is classified as a low priority, and if it is between 300 and 100, it is classified as a medium priority.
Analyze the code, execute it and submit the code in Blockly or Python. You will receive a “Congratulations” message in both cases.

Select one of the two programming languages again and complete the task. Since we recommend being familiar with both, our web app will automatically translate your code written in Blockly to Python and vice versa. Implement the following code yourself, either with Blockly or with Python.

Instructions: Blockly (OPTION I)
 

  1. Replicate the code above in the Blockly interface.  
  2. Click on 'Submit' to check that the result is actually what we wanted.

Instructions: Python (OPTION II)

                
bird_population_density = 200

if bird_population_density > 1000:
    print('Very low priority')
elif bird_population_density > 300:
    print('Low priority')
elif bird_population_density > 100:
    print('Medium priority')
elif bird_population_density > 10:
    print('High priority')
else:
    print('Critical - Emergency priority')
  1. Copy the code from the section above and paste it into the lower code area (on the right-hand side).
  2. Click on 'Submit' to check that the result is actually what we wanted.

Just for fun: What do you think the code will output? Make a guess and run the program to see if your guess was correct. Why do you think this result was output?





 EXERCISE 3
!

The biologist's colleague has made some changes to the code, and the biologist has found that some of the results are incorrect. Can you analyze the code and help the biologist by fixing her error?

Analyze the code, fix the error, and submit it to receive the congratulatory message.

Hint: Make sure that the different usages of if and elif statements are correct. Since it is much easier to fix this error in Python, we have disabled Blockly for this task.

3. Possible solution
 
bird_population_density = 200

if bird_population_density > 1000:
    print('Very low priority')
elif bird_population_density > 300:
    print('Low priority')
elif bird_population_density > 100:
    print('Medium priority')
elif bird_population_density > 10:
    print('High priority')
else:
    print('Critical - Emergency priority')


 
 EXERCISE 4 (OPTIONAL)

The biologist asks for your help in amending the code to recommend the budget that should be invested in the case of “medium priority”, “high priority” and “critical emergency priority”. For “medium priority”, the program should recommend a budget of EUR 15,000 for conservation measures. For “high priority”, the program should recommend a budget of EUR 40,000 and for “critical priority - emergency”, the program should recommend a budget of EUR 100,000.

Follow the instructions, change the program and submit it to see the congratulatory message.

Instructions

Step 1: Customize the code to include budget recommendations:

  • For the “Medium priority” condition, add a “print” command that outputs the following: “Recommended budget for nature conservation measures: 15000 EUR”.
  • For the “High Priority” condition, add a “print” command that outputs the following: “Recommended budget for nature conservation measures: 40000 EUR”.
  • For the condition “Critical - Emergency Priority”, add a “print” command that outputs the following: “Recommended budget for nature conservation measures: 100000 EUR”.

Step 2: Send it and you will see the message “Congratulations”.

Do not assign a value to your input variable when submitting your code. Different values are automatically assigned to test your code.


4. Possible solution
if bird_population_density > 1000:
    print('Very low priority')

elif bird_population_density > 300:
    print('Low priority')

elif bird_population_density > 100:
    print('Medium priority')
    print('Recommended budget for nature conservation measures: 15000 EUR')

elif bird_population_density > 10:
    print('High priority')
    print('Recommended budget for nature conservation measures: 40000 EUR')

else:
    print('Critical - Emergency priority')
    print('Recommended budget for nature conservation measures: 100000 EUR')


 
 EXERCISE 5 (OPTIONAL)

The biologist would like to improve the recommendations. To decide whether a habitat needs to be protected or not, the population density of predators must now also be taken into account. So they need to implement a program that uses logical conditions to check the status of both bird and predator population density and make decisions about conservation measures. 

Follow the instructions, run the program, submit it and receive the congratulatory message.

 

Problem: Predator and prey

Implement a Python program that uses conditional statements to decide whether conservation action is needed. The program should assess the population density status of both birds and predators and decide on conservation measures based on the following conditions: 

  • Conservation measures are required if the bird population density is classified as "critical".
  • Conservation measures are not required if the bird population density is "high".
  • If the bird population density is "moderate", conservation measures are required if the predator population density is "high"; otherwise, they are not required.
  • If the bird population density is "low", conservation measures are required if the predator population density is either "high" or "moderate"; otherwise, they are not required.

Instructions

Step 1: Set up variables

  • Define two variables: bird_population_density and predator_population_density.
  • Important: You can experiment with these variables by clicking "Run", but when you check your answer via "Submit", please delete these lines and do not define these variables.
  • Set their values as strings. For this task, you can use values like "critical", "high", "moderate", and "low". For example:

bird_population_density = "critical"

predator_population_density = "high"

Step 2: Implement conservation logic

  • Write an if statement to check whether bird population density == “critical”. If this is the case, output “Conservation measure required”.

Step 3: Add additional conditions for bird population density

  • Use elif statements for each remaining condition:
    • If bird population density == “high”, print “Nature conservation measure not required”.
    • If bird population density is “medium”:
      • Use an if statement to check whether predator_population_density == “high”. If this is the case, print “Conservation measure required”; otherwise print “Conservation measure not required”.
    • When the bird population density is “low”:
      • Use an if statement to check whether the predator population density is “high” or “medium”. If this is the case, enter “Conservation measure required”, otherwise “Conservation measure not required”.

Step 4: Send

Send the program and view the “Congratulations” message.

Hint: If you do not want to do anything with 'else', but cannot remove 'else', you can simply enter print(“”).

5. Possible solution
# Determine whether conservation measures are required
if bird_population_density == "critical":
    print("Conservation measure required")

elif bird_population_density == "high":
    print("Conservation measure not required")

elif bird_population_density == "medium":
    if predator_population_density == "high":
        print("Conservation measure required")
    else:
        print("Conservation measure not required")

elif bird_population_density == "low":
    if predator_population_density in ["high", "medium"]:
        print("Conservation measure required")
    else:
        print("Conservation measure not required")

else:
    print("")
    
 
!    

Message to take away

We have learned that by using conditions with if, else, and elif statements, we can execute different parts of the program based on conditions we define.