In the real world, there are specific classifications and conditions on every action that occurs around us. A twelve-year-old person is a kid, whereas a thirteen-year-old person is a teenager. If the weather is pleasant, you can make plans for an outing. But if it isn’t, you will have to cancel your plans. These conditions control the coding world as well. You will encounter various coding problems where you will have to print the output based on some conditions.
Luckily, Python has a straightforward command and syntax to solve such kinds of problems. These are called conditional statements. So let’s begin our discussion on conditional statements, their syntax, and their applications.
Basic if Statement (Ternary Operator)
Many programming languages have a ternary operator, which defines a conditional expression. The most common usage is to make a terse, simple dependent assignment statement. In other words, it offers a one-line code to evaluate the first expression if the condition is true; otherwise, it considers the second expression. Programming languages derived from C usually have the following syntax:
The Python BDFL (creator of Python, Guido van Rossum) rejected it as non-Pythonic since it is hard to understand for people not used to C. Moreover, the colon already has many uses in Python. So, when PEP 308 was approved, Python finally received its shortcut conditional expression:
It first evaluates the condition; if it returns True, the compiler will consider expression1 to give the result, otherwise expression2. Evaluation is lazy, so only one expression will be executed.
Let's take a look at this example:
Here we have defined the age variable whose value is fifteen. Now we use the if-else command to print if the kid is an adult or not. The condition for being an adult is that the person’s age should be eighteen or greater than that. We have mentioned this condition in the if-else command. Now let’s see what the output is:
As we can see, we have obtained the output as “kid” based on the value of the age variable.
We can chain the ternary operators as well:
Here we have incorporated multiple conditions. This form is the chained form of ternary operators. Let’s check the output:
This command is the same as the program given below :
The compiler evaluates conditions from left to right, which is easy to double-check with something like the pprint module:
Alternatives To The Ternary Operator
For Python versions lower than 2.5, programmers developed several tricks that somehow emulate the behavior of the ternary conditional operator. They are generally discouraged, but it's good to know how they work:
These are various ways to impose conditions in your code :
We can see that for various inputs, the same output is obtained for the exact value of the variable.
The problem of such an approach is that both expressions will be evaluated no matter what the condition is. As a workaround, lambdas can help:
We obtain the output as follows :
Another approach is using 'and' or 'or' statements:
Yes, most of the workarounds look ugly. Nevertheless, there are situations when it's better to use 'and' or 'or' logic than the ternary operator. For example, when your condition is the same as one of the expressions, you probably want to avoid evaluating it twice:
Indentations And Blocks
Python is very careful of the syntax of programming statements. We have to maintain proper indentation and blocks while we write composite statements like if-else. The correct indentation syntax of the if-else statement is given as follows:
The statements under 'if' are considered a part of one 'block.' The other statements are not part of the if block and are not considered when statements of 'if' are evaluated.
Python will automatically change the text color if you deviate from this indentation and display an error when you run your code. Let's take an example where we intentionally differ from the proper indentation:
We can see here that Python delivers an error message as: "Expected an indented block."
Also, note the color of 'print' in line 3. All the other text is green, while 'print' has the color red. The color variation happens because of the abrupt indentation of 'print.'
Now let us correct the indentation :
When we have maintained the indentation of Python, we get the output hassle-free.
The else And elif Clauses
Suppose your ‘if’ condition is false and you have an alternative statement ready for execution. Then you can easily use the else clause. Now, suppose you have multiple if conditions and an alternative for each one. Then, you can use the elif clause and specify any number of situations. Now let us take an example for each case :
Use of else clause:
The syntax of the if-else statement is straightforward and has been used multiple times in this tutorial. Let us take a fundamental problem: There is a football team selection. The most critical condition for a candidate's eligibility is that he should be seventeen years or older. If his age is greater than or equal to seventeen, the output will be " You are eligible." If the boy is younger than seventeen years of age, the result will be " Sorry. You are not eligible."
Now let’s look at the code for this problem :
Let’s run this code and see what the output is :
The program first asks for the user input of age. We first enter the age as sixteen.
Now let us enter the age as eighteen and observe the output.
Thus we can see that the code assesses the input entered("age") and checks the value against the if-else conditions. If the condition is true, the compiler considers the statement under 'if ' and other statements are ignored. If the condition is false, the compiler executes the statement under 'else,' and all the other statements are ignored.
Use of elif clause :
We use this clause when we have multiple conditions to check before printing the output. The word elif is compact for ‘else-if.' When we use the elif clause, the else clause is optional. But if we want to use else clause, there has to be only one clause and that too at the end of the program.
Let us take a problem. We ask the user to enter a number between one and seven, and we display the corresponding weekday name. Let's look at the program for this problem.
The above-given code has elif as well as else clause.
Now let’s check the output:
The program first asks for user input of a number. Let’s enter four.
Now, let's check the output for the input value twelve.
Thus, the code works for any user-entered input value.
Conditions dominate every aspect of our real-life situations. To simulate these real-life conditions properly in our virtual world of coding, we, the programmers, need a good grasp on the control statements like if-else. We hope that this article helped you in understanding conditional statements and their syntax in Python. The various problems discussed in this article will help you understand the fundamental concepts of if-else statements and their applications.