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 condition age > 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:

  1. Create a variable age with a value of 20.
  2. If age is greater than 17, execute the following indented code.
  3. age is greater than 17, so it prints You 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

By signing up, you agree to the Terms of Service and Privacy Policy.

Or sign up with:

1/10

Introduction to Conditionals | Start Coder