Conditional Statements in Python

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 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 .

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

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

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.

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 .

1 Comment

  1. Thanks sir, waiting for the next lesson 🙂

Leave a Reply

Your email address will not be published. Required fields are marked *