Skip to main content
Practice

The Crossroads of Logical Flow, Conditional Statements

When writing a program, there are times when you need to express logic such as If this situation occurs, do this, and If that situation occurs, do that.

For example, you might need to represent a situation in a program like "If it rains, take an umbrella, otherwise, just go out."

What you need in such situations are conditional statements.

Conditional statements control how a program behaves differently depending on certain situations.

By using conditional statements, you can create various logical flows in a program, rather than just executing commands in order.


Conditional Statements in Python: if, elif, else

In Python, you can write conditional statements using three keywords: if, elif, else.

Each keyword checks a certain condition and decides which code to execute, depending on whether the condition is True or False.

You append a colon (:) at the end of the line containing the conditional statement keyword to indicate the start of the code block that the condition applies to.


if: If the Condition is True

if means "if," and only executes the code block if the condition is true.

For instance, you can perform a specific task only if the condition "x is greater than 10" is true.

if Statement Example
x = 15

# If x is greater than 10, print "x is greater than 10"
if x > 10:
print("x is greater than 10")

In this code, since x is greater than 10, the phrase "x is greater than 10" is printed.

Conditions evaluated by if will consider 0, an empty string, an empty list, etc., as False.


elif: Otherwise, if

elif is short for "else if," and checks a new condition if the preceding if condition is false.

It is used to sequentially check multiple conditions.

elif Statement Example
x = 15

if x > 20:
print("x is greater than 20")
elif x > 10:
print("x is greater than 10")
elif x > 5:
print("x is greater than 5")

In this example, since the first condition (x > 20) is false, it checks the second condition (x > 10).

Since the second condition is true, the phrase "x is greater than 10" is printed.

You can use multiple elif statements as needed to check several conditions sequentially.


else: In All Other Cases

else specifies the code to execute if all preceding if and elif conditions are false.

It is literally used to handle "all other cases."

else Statement Example
x = 5

# If x is greater than 20, print "x is greater than 20"
if x > 20:
print("x is greater than 20")
# If x is greater than 10 but less than 20, print "x is greater than 10"
elif x > 10:
print("x is greater than 10")
# If x is less than or equal to 10, print "x is 10 or less"
else:
print("x is 10 or less")

In this code, since x is less than 10, both preceding conditions are false, so the else block is executed, and the phrase "x is 10 or less" is printed.

Want to learn more?

Join CodeFriends Plus membership or enroll in a course to start your journey.