What is an If Else statement?
Python challenge - If statement
Enter the following code in a Python code editor. Before running the code, what do you think it will do?. Press "F5" then "Enter" to run
The first line declares a variable called SkyColour that holds the value blue
The third line creates a condition based on SkyColour being blue. If it is true that the SkyColour is blue, then the line "The sky is blue today" will be displayed on the screen (line 4)
Line 6 will display "Good bye!" on the screen
If Statement explained
It is important to make the distinction in Python between one equals sign and two equals sign:
= sets a value to a variable
== is a relational operator that means "is equal to". Other examples include:
In this program, we have only coded for when a condition is met i.e. A message is displayed when the age is 18 or above, but we have not coded for if the condition is not met. We can do this by introducing the "Else" statement.
Python challenge - If-Else and the input function
In this example, a user is prompted to enter either a "y" or a "n". Based on the users choice, a condition is met, the code branches and one of the messages is displayed.
Python challenge - Greater than or equal to
Look at the code below. What will happen? What changes can you make to the code display the message "you are old enough to vote!"?
Python challenge - If-Else
In this example, we have coded for both a condition being met or not being met.
Enter the following code in a Python code editor. Note that we have set the food as a kebab. Press "F5" then "Enter" to run
What happens if you change the food to "chips" in both the variable called food and in the IF statement?