If statements are control flow statements which helps us to run a particular code only when a certain condition is satisfied. For example, you want to print a message on the screen only when a condition is true then you can use if statement to accomplish this in programming. In this guide, we will learn how to use if statements in Python programming with the help of examples.
There are other control flow statements available in Python such as if..else, if..elif..else,
nested if etc. However in this guide, we will only cover the if statements, other control statements are covered in separate tutorials.
Syntax of If statement in Python
The syntax of if statement in Python is pretty simple.
if condition: block_of_code
If statement flow diagram
Python – If statement Example
flag = True if flag==True: print("Welcome") print("To") print("BeginnersBook.com")
Welcome To BeginnersBook.com
In the above example we are checking the value of flag variable and if the value is True then we are executing few print statements. The important point to note here is that even if we do not compare the value of flag with the ‘True’ and simply put ‘flag’ in place of condition, the code would run just fine so the better way to write the above code would be:
flag = True if flag: print("Welcome") print("To") print("BeginnersBook.com")
By seeing this we can understand how if statement works. The output of the condition would either be true or false. If the outcome of condition is true then the statements inside body of ‘if’ executes, however if the outcome of condition is false then the statements inside ‘if’ are skipped. Lets take another example to understand this:
flag = False if flag: print("You Guys") print("are") print("Awesome")
The output of this code is none, it does not print anything because the outcome of condition is ‘false’.
Python if example without boolean variables
In the above examples, we have used the boolean variables in place of conditions. However we can use any variables in our conditions. For example:
num = 100 if num < 200: print("num is less than 200")
num is less than 200