Introduction to if statements in Python


Keywords: if statement, conditional statement, else statement, elif statement

if else statement Python

This chapter will cover the if statements in Python. The if statement is a conditional statement that enables us to control the logic of our programs. Since all programming is based on conditions, the if statement can be seen as one of the cornerstones of programming.

What is an conditional statement in Python?

A if statement in Python determines whether the program should perform one or several operations, depending on whether one or more prespecified conditions are reached or not. The condition specified is a logical expression that is either true or false. In other words, we use a logical expression to decide if our programs should execute a certain code or not. Meaning, by using the if statement, you can specify what should happen if a condition is met or not. This creates conditional programming, which is the basis of all logic in a program.

In short, the if statement in Python is:

  • A conditional statement that determine what will happen in the program depending on its conditions.
  • Has a condition that results in a boolean variable (true or false).
  • Forms the basis for logic in our programs.

How to use a if statement in Python?

The if statement is used to decide whether or not to perform an operation. If the condition is true, then the operation is performed. If the condition is false, the operation is not performed. The if statement can be combined with several if statements, so-called else-if and else statements.

The if statement is used to decide whether or not to perform an operation

In this chapter, we will go through how to combine if-statements with else statements, and elif statements to create conditional programming. The flowchart illustrates whether or not an operation should be performed, depending on whether or not the condition in the if statement is met.

If statements Python programming

The different conditional statements in Python

  • If statement: One or more conditions indicate if one (or more) operations are to be performed
  • Elif statement: The operation / operations inside the elif statement (else if) are performed only if the condition of the if statement is false and the condition of the elif statement is true
  • Else statement: Performed when the if and all elif statements are false.

Logical comparison in Python

It might be a good idea to repeat and remind ourselves of the logical operators we saw in the previous chapter. These will be very useful when using the if statement.