Menu Close

python Conditionals- if, elif, and else

Conditionals are absolutely necessary for any computer programming. Conditionals perform calculations depending on whether a condition evaluates True or False. However, else and elif extend the idea by allowing for alternative calculations depending on the evaluation of the original expression.

Basic syntax

Unlike other languages such as Java or C++, python uses indentation rather than braces “{}” to differentiate between sections of code. Due to this, braces and parentheses are nowhere to be found while writing conditionals and switch cases.

Java Example:

int x = 42;
if (x == 42) {
     System.out.println(“Meaning of Life”);
}

Python Example:

x = 42
if x == 42:
     print(“Meaning of Life”)

The 2 segments of code above compare conditionals in Java and Python. Notice how in the Java code, the code to be executed is surrounded by braces “{}”. The braces represent what code to execute if the condition is true. Therefore, the indentation is just for readability rather than necessary for code compilation.

This is the case as the following code will compile and run the same as the Java code above.

int x = 42;
if (x == 42) {System.out.println(“Meaning of Life”);}

Contrastingly, the indentation for our python code is required for the program to run. The indentation takes the place of braces to emphasize better code readability.

For example:

x = 42
if x == 42:
print(“Meaning of Life”)

Output:

IndentationError: expected an indented block

The code will fail immediately on attempt to run, as the program is unreadable to the machine if poor indentation is present.

If statement

The if keyword is imperative to writing any code. It evaluates whether a given statement is True or False, and it will compute code blocks underneath.

The syntax is shown in the following piece of code:

if expression:
     #code

Example 1:

x = 7
y = 10

if y > x:
     print(“Y is larger than X”)

Output:

Y is larger than X

As 10 is more than 7, the expression evaluates True, and the code below runs.

Example 2:

x = False
if x:
     print(True)
print(x)

Output:

False

The if keyword tests whether the expression returns True or False. As the keyword is already False, the code within the conditional is not executed.

Example 3:

x = 512
if x > 0:
     print(“x is larger than 0”)
print(“x is a number”)

Output:

x is larger than 0
x is a number

In this case, the second print() function is executed regardless of whether the conditional executes or not. This is because the second print() function is outside of the conditional, and will always execute once the conditional is finished being executed.

Else and Elif Statements

Many times, if a condition is not met, the programmer often wishes for an alternative segment of code to be executed. There are also cases of additional conditions to be tested if one fails. While in many other languages, the direct solution to this problem would be what is known as a “case/switch statement”, Python has no direct equivalent. However, we can replicate the functionality very closely with the keywords else and elif (short for “else if”).

Case/switch statement

In many languages such as Java and JavaScript, there are special keywords dedicated to problems such as these. These keywords are case and switch, and they have a specific syntax for dealing with multiple different outcomes for one expression.

Java Example

//prerequisite – the variable Weather is a String value which have the possible values of “sun”, “cloudy”, or “rain”.
switch (Weather) {
     case “sun”:
          System.out.println(“Wear a t-shirt”);
          break;
     case “cloudy”:
          System.out.println(“Wear a jacket”);
          break;
     case “rain”:
          System.out.println(“Bring an umbrella”);
          break;
}

In the code above, the system will print different tips depending on the weather. For example, if the Weather variable is “sun”, the system will print “Wear a t-shirt”.

However, in Python, to replicate the same functionality, we would need a series of else and elif statements. The elif statement takes another expression and only executes if the if statement preceding it evaluates False. Once one elif statement evaluates True, all subsequent elif and else statements will be ignored regardless of whether they evaluate true or not.

The else statement takes no arguments and will only execute should all the preceding if and elif statements evaluate False.

Example 1 (Same hypothetical as the Java Example):

#prerequisite – the variable Weather is a String value which have the possible values of “sun”, “cloudy”, or “rain”.
if Weather == “sun”:
     print(“Wear a t-shirt”)
elif Weather == “cloudy”:
     print(“Wear a jacket”)
else:
     print(“Bring an umbrella”)

Example 2:

Suppose there is an algorithm for determining the mark of students based on their percentage. The code might look something like the following:

#prerequisite – the variable Mark is an integer value which is between 0 and 100 inclusive.
if Mark == 100:
     print(“Congrats! You scored perfect!”)
elif Mark > 94:
     print(“Wonderful! You got an A+”)
elif Mark > 85:
     print(“Good job! You got an A”)
elif Mark > 69:
     print(“You got a B”)
elif Mark > 54:
     print(“You got a C”)
else:
     print(“Failed.)

The example above works as once it reaches one of these, the rest will no longer execute.

Nested conditionals

Often, there are multiple expressions that need to be tested, or another condition to be tested if the original expression is True. This is where we use nested conditionals – which just means a conditional within a conditional.

The inside conditional will only be evaluated if the outside one evaluates true, much like any other piece of code.

Example:

x = 50
if x > 20:
     if x > 40:
          print("x is larger than 40")
     else:
          print("x is between 20 and 40")

Output:

x is larger than 40
Posted in Embedded Programming Language, Python

Related Articles

Leave a Reply

Your email address will not be published.

Leave the field below empty!