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.
If you have forgotten your Replit account user name or password, ask your Coder Coach.
At the ‘predict’ & ‘run’ stages students work entirely with example code. They should inspect it carefully and write a prediction about what it will do.
They then run the code and compare the result to their prediction.
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.
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 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")
Make sure to check for the following mistakes:
==
) when checking that two pieces of data are the same.