replit

Before you start this course, you must login to Replit

If you have forgotten your Replit account user name or password, ask your Coder Coach.

CoderSports

7-3-Modify

Task – Modify

Instructions:

Adapt the code so that:

  • The user is asked at the end if they guessed correctly
  • If they did, display a “Well done” message
  • If they didn’t, display a “Never mind” message
  • As well checking whether the answer is too high or too low, add a line that checks whether the guess is equal to the answer and if it isn’t, displays a “Bad luck” message
  • Add comments to explain what you have changed.

If…Else Statements

What is it

These are statements that allow Python to perform different tasks in different situations.

This is used all the time in real life. One example could be:

IF it is raining, THEN I will take my umbrella

In the example, the second part ONLY happens if the first part is true.

Boolean conditions

If…Else statements rely on a boolean condition to decide whether or not to run the code.

Boolean conditions check if something is True or False.

Boolean conditions are written using logical operators. These are:

Operator Definition Example
== Equal to/Same as (a single = is used to store data in a variable, so Python uses double = to compare two pieces of data) if weather == "rain"
If it is raining
!= Not Equal to if weather != "snow"
If it is not snowing.
> Greater than if age > 10
If the age is greater than 10.
>= Greater than or Equal to if age >=10
If the age is greater than 10, OR if the age is 10.
< Less than if age < 18
If the age is less than 18
<= Less than or Equal to if age <=18
If the age is less than 18, OR if the age is 18

When using the == operator, case matters. Hello World is not equal to hello world.

Code Examples

# Code with one statement
if condition:
    print("Run this code")

# Code with else statement
if condition: 
    print("Run this code if the condition is True")
else: 
    print("Run this code if the condition is False")

Help! My Code Does Not Work!

Make sure that you check for the following things:

  • A colon at the end of each if and else line.
  • Each branch is indented unsing the TAB key (not just spaces)
  • No condition after ‘else’
  • A double equals in the condition (==) when checking that two pieces of data are the same.

Hints