One of the widely-used flow control statement type in Python is if..else statement. Through flow control statements, we can figure out which statement we need to execute next. Furthermore, while and for statements belong to the same group.
Let’s say we have defined a condition which needs to be evaluated. And, there are two different outcomes to it – A and B. So, if the condition is True then, A needs to be executed. Otherwise execute B.
The following is the syntax for if..else statement –
if (condition): execute A else: execute B
We cover it more with couple of examples in next section.
if..else statement in Python
Example I. We take integer input from the user to determine whether the input is a positive integer or negative integer. Here, positive integers the those numbers whose value is greater than zero. And, negative integers are less than zero.
num = int(input("Enter an integer value: ")) if (num > 0): print("It's a positive integer!!") else: print("It's a negative integer!!")
Now, if we provide 7 as input, it would show –
It's a positive integer!!
or -5 as input, the outcome will be –
It's a negative integer!!
But, what about 0 (zero)? Even in that case it would consider it as negative integer which is incorrect. We can use elif to rectify the code.
Example II. As we have already seen in Example I, we needed something else to ensure our program worked correctly. What we miss here is “elif“. Nothing new here, with the help of elif we introduce a new condition. Let’s see how it works –
num = int(input("Enter an integer value: ")) if (num > 0): print("It's a positive integer!!") elif (num < 0): print("It's a negative integer!!") else: print("It's a zero!!")
Now, again input positive, negative integer values and a zero. You would see things fall in place this time around. With elif, we asked the interpreter to check for additional condition if the above condition is False. And, if both the conditions with if and elif are False then, execute else block.
The syntax for if..elif..else statement is –
if (condition): execute A elif (condition): execute B else: execute C
Note: Please take care of the indentation while writing the code. Otherwise, it may lead to unnecessary errors.
In conclusion, we have discussed if..else statement in Python.