IF Statements Lesson 1

An If statement is a control structure. We use if statements to programme an automatic response from a computer.

Think about an every day device such as a fire alarm in your house. An if statement is programmed into the device memory to beep loudly if it detects carbon monoxide. Look at the flow chart below.
FireAlarm

If statements are all about programming the computer to make a response that is pre-planned. The computer is programmed to check if something is true or false. If something it is testing is True

, the computer will take an action. If something is  False , it will take a separate action.

 

Let’s look at an example.

Muhammad scored 79% in his History test. He needed 50% to pass. The following is an example of how we could code a programme to state whether Muhammad has passed or failed.

if result >= 50:
    print("Pass")
else:
    print("Fail")

 

Comparative operators

Programming languages use comparative operators to help determine if a test is True or False. They are:

  • > More than
  • < Less than
  • >= More than or equal to
  • <= Less than or equal to
  • != Not equal to
  • == equal to


Challenge 1

Lets use Python to write a Galatasaray crowd chant (translated into English). Fans often encourage the opposite side of the stadium to join in and chant by calling out “the opposite side is red!“. This is then reciprocated when the opposite fans calling out “the opposite side is yellow!“.

We will have a variable that is used to store a colour. Use the example below to write an if statement to print out “the opposite side is red!” if the variable colour is equal to yellow.

var = "blue"
if var != "blue":
    print("something")
else:
    print("something else")

[expand title=”ANSWER”]

colour = "yellow"
if colour != "yellow":
    print("the opposite side is red!")
else:
    print("the opposite side is yellow!")

[/expand]

 

Challenge 2

Now you will write a programme for an electronic thermometer. The Thermometer takes readings using a sensor and outputs a message depending on the heat reading.

If the temperature is above 20 degrees, the programme should print out

 

Answer

Posted in CS, Uncategorized.

Leave a Reply

Your email address will not be published. Required fields are marked *

*