Learn Programming through LIVE online classrooms

# Python Conditional Statements

Posted in Python  If you are just starting to learn Python, you will soon understand that conditional statements in Python are really useful and perform a variety of actions depending on the conditions or cases and whether they are true or false.

## Python Conditional Statements

The different types of statements in Python and their explanations are given below:

### If Statement

The ‘if’ statement is used for decision making. Once the constraints are defined, it will run the body of the code only when ‘If’ statement is true.

Basic Syntax:

```if expression
statement
```

Example:

```a, b = 11,32
if (a<b);
qw = “a is less than b”
print (qw)
```

### If-Else Statement

This statement comes in when the If condition is not met. The If-Else statement provides and If statement and an Else statement.

Basic Syntax:

```If expression
statement

else
statement
```

Example:

```a, b = 11,32
if (a<b);
qw=”a is less than b”
else
wq=”b is less than a”
print (qw)
```

### Else-If (elif) Statement

The Else-If statement is used when the else condition might not suffice. This is used mostly in those cases when you have to justify more than two results.

Basic Syntax:

```If expression
statement

elif expression
statement

else
statement
```

Example:

```def main():
q,r =3,3
if(q< r):
yz= "q is less than r"
elif (q == r):
yz= "q is same as r"
else:
yz="q is greater than r"
print(yz)
```

### Nested Else-If Statement

The nested Else-If statement is used when there are multiple results need to be defined.

Basic Syntax:

```If expression
statement
elif expression
statement
elif expression
statement
elif expression
statement
.
.
.
else
statement
```

Example:

```Cost = 125
#country = "IN"
if Cost <= 50:
print("Shipping Cost is 25")
elif total <= 100:
print("Shipping Cost is 10")
elif Cost <= 150:
print("Shipping Costs 5")
else:
print("FREE")
```

### Switch Statement

A switch case statement is a multi-branched statement which compares the value of a variable to the values specified in the cases. Python does not have a switch statement but it can be implemented using other methods, which will be discussed below.

Basic Syntax:

```function(argument){
switch(argument) {
case 0:
return "This is Case Zero";
case 1:
return " This is Case One";
case 2:
return " This is Case Two ";
default:
return "nothing";
};
};
```

#### The Switch Case Statement

In general computer programming and associated languages, the switch case statement is a form of selection means to alter the control flow of program execution through the value of a predefined variable or expression, using the process of search and select. The switch statement is to some extent similar to the if statement, which is used in a variety of programming languages, including C, C++, Visual Basic, Python, Pascal and Java. Many variations of the statement are used in other languages, with names such as case, inspect or select.

In the majority of languages, the typical syntax of the switch case statement is as follows:

• First the control expression is defined, upon which the switch statement is implemented
• Successive lines defining the case values and subsequent statements which will be executed in case of a match
• An ending declaration to conclude the said statement

#### Implementation of Switch Case in Python

Unlike many other languages, Python does not have a default switch construct. This may feel odd if you are from a Java or C++ background, but in Python, Switch needs to be implemented in a roundabout way, rather than directly. To get around this, one would need to use the pre-built dictionary construct of Python to define the cases and the outcome, if and when a case is met. Below we take an example, where we will define a function month() to tell us a certain month of the year. The dictionary performing the mapping in this is called switcher.

Syntax

```>>> def month(i):
switcher={
1:'January',
2:'February',
3:'March',
4:'April',
5:'May',
6:'June',
7:'July',
8:'August',
9:'September',
10:'October',
11:'Novmber',
12:'December'
}
```

return switcher.get(i,"Invalid month of the year")

Now, we make calls to month() with different values.

```>>> month(1)
'January'
>>> month(3)
'March'
>>> month(13)
'Invalid month of the year'
>>> month(10)
'October'
```

As you can observe, the switcher will only print out the values provided to it, and will return a ‘Invalid month of the year’ when another value is input. It happens as it was told to do so using the get() method of a dictionary.

To implement the switch case in Python, we can also use

• Python Functions & Lambdas
• Python Classes

## Python Functions & lambdas

Switch case can be implemented in Python using Python functions & lambdas, the syntax of which is given below:

```>>> def zero():
return 'zero'
>>> def one():
return 'one'
>>> def example(i):
switcher={
0:zero,
1:one,
2:lambda:'two'
}
func=switcher.get(i,lambda :’Invalid’)
return func()
```

When different values are passed through it, we get:

```>>> example(7)
‘Invalid’
>>> example(1)
'one'
>>> example(3.12)
'Invalid'
```

## Python Classes

Using the concept of Classes, we can implement Switch case with the following syntax:

```>>> class Switcher(object):
def example(self,i):
method_name='number_'+str(i)
method=getattr(self,method_name,lambda :'Invalid')
return method()
def number_0(self):
return 'zero'
def number_1(self):
return 'one'
def number_2(self):
return 'two'
```

When different values are passed through it, we get:

```>>> s=Switcher()
>>> s.exampe(2)
'two'
>>> s.example(1.2)
'Invalid'
>>> s.number_1()
'one'
```

## Switch Case vs If Else

In computer programming, both ‘if-else’ and ‘switch’ statements are selection statements. A selection statement will alter the flow of the program to the specific set of statements depending upon the nature of the condition, which is either ‘true’ or ‘false’. The fundamental difference between the if-else and switch statement is that the if-else statement will select the execution of the statements on the basis of the evaluation of the expressions in the if statements, while the switch statement selects the execution of the statement on the basis of the keyboard command.

Implementation in other languages

If-Else

The if-else is a selection statement in object-oriented programming. Below is the general form of an if-statement:

```if (stated expression) {
statement (X)
} else {
statement (Y)
}
```

Here, both ‘if’ and ‘else’ are keywords, and the above-mentioned statements can either be a single statement or a set of statements. In the if statement, the expression can be an integer, character, pointer, floating-point or Boolean type. If the expression returns ‘true’, the statement(s) inside if will be executed, otherwise, the statement(s) inside the else is executed.

Let us understand better with an example:

```int i=1, j=2;
if (i==1 & j==2){
cout<< "Yes";
}else{
cout<< "No”;
}
```

Since the expression is true, the output will be ‘Yes’

Switch

As discussed above, the Switch statement is basically a multiple choice selection statement. The general form of a switch statement is given below:

```switch( expression ){
case constant1:
statement(s);
break;
case constant2:
statement(s);
break;
case constant3:
statement(s);
break;
.
.
default
statement(s);
}
```

The expression above will only check for equality and nothing else. The expression will be confirmed against the constants in the case statements and if a match is found, the statement associated with the case will be executed, up until a ‘break’ is defined. As the break statement is not obligatory in case statements, the execution will not stop till the end of the statement if a break is missing. Here is an example of a switch statement executed in C++:

```int c;
cout<<" choose a value from 1 to 3"; cin>>i;
switch( i ){
case 1:
cout<<"you choose Red";
break;
case 2:
cout<<"you choose Blue";
break;
case 3:
cout<<"you choose Orange";
break;
.
.
default
cout<<"you choose nothing";
}
```

In the above code, the value of i decides which case will be executed through the value provided by the user. If the user gives a value other than 1,2 and 3, the default case will be executed.

### Comparison between If-Else and Switch Case Statements

 Comparison Parameter Switch Case If-Else Execution The user decides which statement will be executed The output of the expression inside the if statements will decide which statement is executed Evaluation Switch statements can only evaluate character or integer value If-Else statements can evaluate integer, character, pointer, floating-point and Boolean types Test The switch statement tests for equality The If-Else statement tests for equality and logical expression Expression A single expression is used for multiple choices Multiples statements are used for multiple choices Sequence of Execution Either the if statement is executed or the else statement The switch statement will execute one case after another until a break occurs or the end of the statement is reached Default Case If the input value does not match any of the cases inside the switch statement, then the default case is executed If the expression inside the if statement is false, then by default the else statement is executed Ease of Editing Editing switch case statements is easy due to cleaner code and easily recognizable cases If nested if-else is used, editing the statements might be a hassle

## Conclusion

Well this is almost everything you should know about the Python Switch Case statement. This selection statement makes error detection easier as the program is divided into units through the specified cases. Although it can only check for equality, it is really helpful when you wish to keep the code clean when many values for a variable need to be compared.

If you have any questions regarding the Python Switch Case Statement or have a suggestion to make, feel free to do so via the dedicated comments section below.

Just started coding in Python? Check out our numerous beginner courses on Python programming. 