Skip to main content

Python Conditions and If statements

Conditions in Python work like the comparisons you know from math class:

  • a == b: equal
  • a != b: not equal
  • a < b: smaller than
  • a <= b: smaller than or equal
  • a > b: larger than
  • a >= b: larger than or equal

You will meet these comparisons in many places, above all in loops and in "if statements".

To write an "if statement", begin with the if keyword.

Example

A first if statement:
Prompt
Write a Python program that assigns 33 to a and 200 to b, then uses an if statement to check if b is greater than a and prints a message.
Output: complete Python program

How If Statements Work

An if statement looks at a condition, meaning an expression whose value is either True or False. When the answer is True, Python runs the statement's code block. When it is False, Python skips that block.

Example

Testing whether a number is above zero:
Prompt
Write a Python program that checks if a number is positive using an if statement and prints a message.
Output: complete Python program

Indentation

Many languages mark a block of code with curly brackets. Python uses indentation instead: the whitespace at the start of a line is what defines scope in your code.

Note: Spaces and tabs both work, but every statement in one code block has to be indented by the same amount.

Example

Leaving out the indentation gives an error:
Prompt
Write a Python if statement without proper indentation to demonstrate that Python will raise an error.
Output: complete Python program

Multiple Statements in If Block

An if block is not limited to one line. Put as many statements in it as you need, and indent each of them to the same level.

Example

An if block that runs three statements:
Prompt
Write a Python program that checks if age is 18 or older and prints multiple statements inside the if block.
Output: complete Python program

Using Variables in Conditions

A boolean variable needs no comparison operator: you can place it straight after if.

In fact, an if statement can judge many kinds of values as True or False.

The values that count as False are zero (0), empty strings (""), None and empty collections. All other values count as True.

So positive numbers like 5, negative numbers like -3 and every string with at least one character count as True. That even covers "False", because the string is not empty.

Example

A boolean variable as the condition:
Prompt
Write a Python program that uses a boolean variable directly in an if statement to print a welcome message.
Output: complete Python program