Technology Inside Out!

Index ¦ Archives ¦ Atom ¦ RSS

Conditional Statements in Python

Conditional Statements in python

In this tutorial we will discuss about conditional statements in python. Conditional statements are used to perform different computation based on the Boolean expression which turns out to be true or false . Boolean expression is on which these conditional statement works. Various Conditional statement used are:

  • If
  • Else
  • Else if

If condition

The general syntax for using if statement is

if (Boolean expression) :
   code  #indentation is required

if is a keyword used for if statements ,it is a followed by a boolean expression which is evaluated  . Now question arises is why space is given in front when we have written code statement . This is because as no brackets are used to hold the computations after the if statement as this is a case in c++,java which uses curly brackets {}. The symbol : signifies that from here if block starts .

In Python indentation is given rather than using brackets . If we not give the indentation compiler will give an error in case when no line is there in the if block .

a=2;
if(a==2):
print a
else
print "NO"

Screenshot-7

If statement can be used with else statements and can be used alone . If the condition evaluates to true then code inside if block is executed otherwise it is skip to the next line.

else condition

The syntax of the else statement is

else :
  code

Here else is a keyword used and there are no brackets used as in if statement ,else is also followed by the code segment and indentation is required. Else statement are followed by if statement and cant be used alone . Compiler checks the if block first if Boolean expression doesn't come out to be true ,code inside else statement gets executed.

Example

a=2
if(a==2):
 print "YES"
else :
 print "NO"

In this example a has been assigned a value 2 , after that value of a is checked by using if statement . The statement (a==2) means a is compared to the value 2 if it comes to be true if statement will execute otherwise else statement will execute. The output for this case will be "YES".

Elif

To avoid multiple if else statements we use else if .It is just like a else followed by a if .elif is a keyword used for else-if statemnts . This example will tell the use of elif keyword.

a=9
if(a%2==0):
 print "YES"
elif (a%3==0):
 print "YES"
else
 "NO"

Here first if condition is checked ,if it comes out to be false it goes to elseif block and if that also comes to be false ,it finally goes to else block.

\% is an operator used to find modulus of a number .It find the remainder when two numbers are divided.

Any doubts related to conditional statement can be asked in comment section .In next tutorial we will discuss about looping .

© The Geeky Way. Built using Pelican. Theme by Giulio Fidente on github.

Disclaimer Privacy policy