Python: Conditional Constructs:if-else..

We have completed very basic of Python til now. In some situations depending on the conditions the set of codes will be executed. In python, we have conditional constructs which will help us program more efficiently.

Conditions:

We have few conditional operators in python, which will help us in comparing two values and give the result in Boolean value(True or False).

Enter the following code in terminal to see the results:

[python]
>>> 1>4
False
>>> 5>3
True
>>> 1==1
True
>>> 1=1
SyntaxError: can’t assign to literal
>>> 9!=8
True
>>> 100>=1212121
False
[/python]

NOTE:We cant use assignment operator(=) because its used for storing value in variable, so we use == operator(double equal symbol) for Equality comparison.

Similarly, we can use comparison operator on Strings.

[python]
>>> ‘Mr.Spark’ == "Mr.Spark"
True
>>> ‘Mr.Spark’ < ‘cemicolon’                                   #ASCII code of c(99) > M(77)
True
>>>”PYTHON” ==”python”
False
[/python]

That was something about the comparison operator, lets move onto something more interesting: conditional constructs. Using Conditional Constructs, we can control the flow of the program.

The various Conditional constructs are if, if…else, elif, and nested if.

The if Statement

The if statement contains a logical expression with which the data will be compared, if the condition is evaluated successfully then it will execute a certain a block of code or else if the condition is false then it will not execute the block of code.

Syntax:
if expression:
#Block of code

Note: We know that Python uses indentation to group certain part of code. When any Conditional construct is met, the following code will be automatically indented.

Example:

[python]
#!/ur/bin/env python
var_if=raw_input("Enter true to test if its working:")
if var_if==’true’:
print "Its working!!"
[/python]

Output:

[python]
>>> Enter true to test if its working:true
Its working!!
[/python]

The Else Statement:

Else is used in combination with if Statement. If the if statement condition fails(resolves to 0 or false value) then it executes the block of code following the else statement. This is Optional instruction.

if expression:
   #block of statement if value is true
else:
   #block of statement if value is false

In the previous example, we don’t have anything to execute in case <em>if</em> statement so lets modify the code here.

Example:

[python]
#!/ur/bin/env python

var_if=raw_input("Enter true to test if its working:")
if var_if==’true’:
print "Its working!!"
else:
print "Resulted into False,Still working"
[/python]

Output:
[python]
>>> Enter true to test if its working:false
Resulted into False,Still working
[/python]

The elif statement:

We have situation when we have multiple comparison to make, for that we use elif statement. Lets put it technically, elif statement allows you to check multiple expressions for truth value and execute a block of code as soon as one of the conditions evaluates to true. Like else,elif is also an optional statement.

Syntax:

if expression1:
   #Block of code
elif expression2:
   #Block of code
elif expression3:
   #Block of code
else:
  #Block of code

Example:

[python]#
!/ur/bin/env python
# -*- coding: utf-8 -*-
_if=raw_input("To know Creator\nMenu\n1.Python\n2.C++\n3.Ruby\nEnter number:")
if var_if==’1′:
print "Guido Van Rossum"
lif var_if==’2′:
print "Bjarne Stroustrup"
elif var_if==’3′:
print "Yukihiro “matz” Matsumoto"
else:
print ‘Wrong value exiting!!’
exit()
[/python]


Output:

[python]
To know Creator
Menu
1.Python
2.C++
3.Ruby
Enter number:2
Bjarne Stroustrup
[/python]


The Nested if..elif..else construct

There will be situation where we want to check for another condition when it the condition results to true.

Syntax:

if expression1:
   #Block of code
   if expression2:
      #Block of code
   elif expression3:
      #Block of code
   else
      #Block of code
elif expression4:
   #Block of code
else:
   #Block of code

Example:

[python]
#!/ur/bin/env python
food=raw_input(‘Burger or Meals?’)
if food=="Burger":
burger=raw_input(‘Veg or Non veg’)
if burger==’veg’:
print ‘Costs 40rs!!’
else:
print "Costs 50rs"
elif food=="Meals":
meals=raw_input(’1.North Indian\n2.South Indian\n3.Chinese’)
if meals==’1′:
print ‘Costs 70rs’
elif meals==’2′:
print ‘Costs 80rs’
else:
print ‘Costs 75rs’
else:
print ‘Do nothing’
[/python]

Output:

[python]
>>>
Burger or Meals?<em>Meals</em>
1.North Indian
2.South Indian
3.Chinese<em>2</em>
Costs 80rs
[/python]

Advertisement