Introduction to Conditionals
In life, we often perform actions based on conditions. For example: if it rains, I'll take an umbrella. If I have time, I'll come.
In programming, we do this using the if
statement. For example:
age = 20
if age > 17: # if age is greater than 17, execute:
print("You can enter")
# Prints: You can enter
What does the if
statement consist of?
- The keyword
if
followed by a conditionage > 17
, which is either true or false, followed by a:
. - The code that we want to execute if the condition is true. This code is indented (either using the Tab key or four spaces).
Now let's go through the code step by step:
- Create a variable
age
with a value of20
. - If
age
is greater than17
, execute the following indented code. age
is greater than17
, so it printsYou can enter
.
Instructions
Create a variable monitorPrice
with a value of 3000
.
Create an if
statement with the condition monitorPrice < 4000
, which when true, prints I'll buy the monitor
.
Start programming for free
1/10