What is the IF condition

In the Python programming language, as in all others, it is possible to verify the validity of a condition using the IF mechanism. What does that mean?

Simply put, you can check whether a condition is true or false. For example, if a variable has a certain value, if a variable is True, if a variable belongs to a certain type, or if a text string is equal to another.



The IF syntax

The IF syntax follows this logic:

If a condition is true, do something.
Else if none of the previous ones are true, but this one is, then do this [repeat as many times as you want]
Else if none of the stated conditions are true, then do this (ends the IF block)

In Python, this translates to:



The if, elif and else statements

if → if this condition is true, do this.
elif → if none of the previous ones are true, but this one is, do this.
else → if none are true, do this.

Now let's look at some code examples.



Code example

Here is a complete example:

                        
x = 2

if (x == 2):
    print("x is equal to 2")
elif (x == 3):
    print("x is equal to 3")
else:
    print("x is neither 2 nor 3")
                        
                    



Code explanation

What does this code do:

It declares the variable x with a value equal to the number 2.

It checks whether x is equal to 2 (in Python, to check if something is equal to something else, you use the double = sign). If it is, it prints "x is equal to 2".

Alternatively, if x is not equal to 2, so the first condition is not met, it checks if x is equal to 3 (elif). If it is true, it prints "x is equal to 3".

Otherwise, if none of the previous conditions are true, it prints "x is neither 2 nor 3".

In this case x is equal to 2, so the program will print:



Program output

x is equal to 2



The print() function

It is not mandatory to include elif in an IF statement, nor is it mandatory to include else.

Note that the print() function in Python allows you to print to the screen. If we want to use it to print the value of x:

print(x)
If we want to use it to print "Here is the value of X: [value of x]":
print(f"Here is the value of x: {x}")



Author: Valerio De Marchis

Date: 22/07/2026