Skip to main content

Python Conditional statements

Python conditional statements are used to restrict the process for certain conditions met. In this tutorial we will learn about  conditional statements, simple if and  if elif statements.

Techtuts provides an example along with concepts. You have to workout the example programs for good and well.

There are three  types of if statements are available in  python

  1. Simple if ....  Statement
  2. if ....   else: .... Statement
  3. if .... elif: .... Statement

Simple if  cond: ....  Statement

  Python  executes the programing line by line. we  can use Simple if statement the redirect the line by line execution by certain condition is true

if condition:

     statements

Example

x = True
if  x:
    #execute conditon
y =10
if y:
    print(y) 
    #print 10
print (x)
#print  True

Simple if cond: ....  else: .... Statement

 Simple if ....  else: .... Statement  execute true part and false part if condtion is failed.

if condition:

    #statements

else:

    #statements

Example

x = 5
if x>5:
    print("x is greater than 5") 
else:
    print("x is less than or equal to 5")

Simple if cond: ....  elif cond: ....  else: .... Statement

the if ....  elif: ....  else: .... Statement  used to checks  and executes the more than one conditions and statements.  we can use n number of if cond: .... elif cond: ...

if condition1:

     #statements

elif condition2:

     #statements

else:

     #statements

Example

x = 5
if x>0:
    print("x is Positive Number") 
elif ( x% 2) == 0 :
    print ("x is  Even Number")
elif ( x% 2) == 1 :
    print("x is Odd Number")
else:
    print("x is Negative Number")