Control flow statements: if, if-else and if-elif-else
if
statement is a control flow statement which allows a piece of code to be executed if a condition is satisfied. elif
is a short form of else if, its a second conditional statement, which follows the if condition.
The if
condition can exist by itself, elif can follow the if statement, else
can follow if and elif statements. else is the statement which catches the flow whenever the condition inside if statement is false.
Here's an example of a standalone if statement
x = 13
if x < 0:
print("x is negative")
We can add a else statement to this to catch positive numbers like below:
x = 13
if x < 0:
print("x is negative")
else:
print("x is a positive number")
To find out if x is a single digit number we can add an elif statement in-between the if and else statements
if x < 0:
print("x is negative")
elif x >= 1 and x <= 9:
print("x is a single digit number")
else:
print("x is a positive number greater than 10")
There can be multiple elif statements following an if statement. Here's an example of the if-elif-else statement cluster called a if-elif ladder.
x = 13
if x < 0:
print("x is negative")
elif x == 0:
print("x is zero")
elif x >= 1 and x <= 9:
print("x is a single digit number")
elif 10 <= x <= 19:
print("x is in it's teens")
else:
print("x is a positive number greater than 20")
Python also supports a feature called chained comparison, which allows comparisons like (10 <= x >= 19
) which can also be written in traditional forms as (x >= 10 and x <= 19
), this is a shorter and more expressive form of writing a conditional statement.
The new way of conditional statement is making me curious, let's find out what other forms and expressions there are. Let's also reconfirm some expressions that we may have learnt in Java or C.
P.S: all the code used in this tutorial is available in github
References:
No comments:
Post a Comment