Menu
Coddy logo textTech

If Statement

Part of the Fundamentals section of Coddy's Python journey — lesson 20 of 77.

If statements allow us to execute code with conditions.

For example, let's look at the following code:

age = 20
status = "Child"
if age > 18:
	status = "Adult"
age += 1

The above code checks whether the age variable is greater than 18. If it is, it will set status to hold "Adult" string.

In the end, the code will increment age by 1 whether the age is greater than 18 or not.

To use an if statement, we need to add a colon : at the end of the if, and everything that is inside the if is indented with 4 spaces or tab:

if condition:
    code
    code
    code

If the condition is True, we will enter the code block inside the if (the indented code).

challenge icon

Challenge

Beginner

The variables a and b have missing values, fill them so that the code inside the if statement will be executed! (make sure the if condition is true)

At the end of the program, the value of c should be 3.

Bonus: try to find more than one solution!

Cheat sheet

If statements in Python allow conditional execution of code:

if condition:
    # Indented code block
    # Executed if condition is True

Key points:

  • Use a colon : after the condition
  • Indent the code block with 4 spaces or a tab
  • The indented code executes only if the condition is True

Example:

age = 20
status = "Child"
if age > 18:
    status = "Adult"
age += 1

In this example, status becomes "Adult" because age is greater than 18.

Try it yourself

a = ?
b = ?

# Don't change below this line
c = 0
if a >= b and not b < 10:
    c = 2

c += 1
print(f"c = {c}")
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Fundamentals