The if statement

The easiest method for making a decision in Python is by using the if statement. This enables you to select the actions to perform if the evaluated condition is true. The syntax of the if statement is:

if condition:

As you can see, the if statement begins with the keyword if. After the if keyword comes a condition that will be evaluated. The condition must end with a colon (:). After the condition come the statements that will be performed if the condition evaluates to true. Note that the text indentation is important in if statements and affects the meaning of code, so make sure to indent the statements.

Consider the following example:

x = 5

if x == 5:
     print('Hello world!')

In the example above the value of x is set to 5. The if statement will evaluate whether the x = 5 and print Hello world! if the condition is evaluated to true. Because x indeed is 5, the text Hello world! will be printed.

Note that we’ve used the equality operator (==), and not the assignment operator (=) to evaluate the condition. The equality operator checks whether the two values are equal.


Here is another example:

x = 5

if x == 6:
     print('Hello world!')

In the example above the text will not be printed because x is not equal to 6.

One more example:

myName = 'Mark'

if myName == 'Mark':
     print('Hi Mark!')

In this case, the text Hi Mark! will be printed because the variable myName indeed holds the string Mark:

Hi Mark!
Geek University 2022