If Statement in Python

If statement in Python programming allows you to control and execute a specific block of code if the condition is true or false based on some specific condition.

General form of If Statement


if(this condition is true)
    execute this statement

Comparison Operators

Expression Description
x == y x equals y.
x < y x is less than y.
x > y x is greater than y.
x >= y x is greater than or equal to y.
x <= y x is less than or equal to y.
x != y x is not equal to y.
x is y x and y are the same object.
x is not y x and y are different objects.
x in y x is a member of the container (e.g., sequence) y.
x not in y x is not a member of the container (e.g., sequence) y.

Program Comparing Two Strings

Program

val = "Khan" == "Khan" #comparing and assigning to 'val'.
print(val) #output is 'True'.
Output
True

Program Using If Statement
Program

num = input("Please Enter Ur Name: ") #User enter value assigning to 'num'.
if num == "HiLaLs": #if 'num' value is Equal to 'HiLaLs' then
                    #U also write If Statement like 'if (num == "HiLaLs"):'.
   print("Hi M'r HiLaLs") #print this.
Output
Please Enter Ur Name: HiLaLs
Hi M'r HiLaLs

Program Using Multiple If Statement
Program

num = int(input("Enter a Number: ")) #User enter value converting to Integer
                                     #and assigning to 'num'.
if num < 10: #if 'num' value is less then 10 then
    print("Entered value is Less then 10!") #print this.
if num == 10: #if 'num' value is equal to 10 then
    print("Entered value is Equal to 10!") #print this.
if num > 10: #if 'num' value greater then 10 then
    print("Entered value is Greater then 10") #print this.
Output
Enter a Number: 223
Entered value is Greater then 10