Mastering Conditional Statements in Python: A Comprehensive Guide

Mastering Conditional Statements in Python: A Comprehensive Guide

Decision making in Python programming and software development

In this article, we'll learn in-depth about conditional statements and their examples in Python programming language. Most applications if not all have one or more requirements/decisions designed to restrict or grant access or continue the flow of its execution.

Checkout the previous article titled: Understanding Python Data Types: A Comprehensive Overview in this Python series.

Condition

A requirement, decision, action or something that must be done or satisfied for something to happen or take effect. For example, there's an if in the mind of this reader saying: if conditional statements in Python are simple to comprehend i'll continue else i'll try another language.

Conditional Statements in Python

Conditional statements in Python Programming, are statements that define the requirements or something that must be done/satisfied to have access to the outcome. Conditional statements are important when building applications because decision-making is the core part of every functionality. Python programming language uses the if, elif and else to define conditional statements.

Conditional Statement Structure

Python conditional statement begins with the check for the condition using the if..elif..else keyword while the next line indicates the action or functionality to execute after the condition is met. Just like a defined conclusion.

if condition:           
   # what to do based on the first outcome of the condition
   # could be false or true
elif condition:
    #what else to check if the first condition is not been met
else:
    #alternative conclusion when conditions are not met

Let's take a look at the keywords (if, elif and else) used in defining conditions in Python programming.

IF

The if is used to determine what should happen based on the status of the condition which most times evaluates to be true or false. Several operators can be used to check if the condition is satisfied or not. The satisfaction of the condition triggers or grants access to the expected outcome/functionality on the next indented line.

if 2 > 2:
    print(True)

SHORTHAND IF

if 2 > 2: print("2 is greater than 2")

The and, or, not operator can be used to check multiple conditions on a single line statement.

AND

The "and" keyword checks to ensure the conditions are evaluated to be true.

name = "EC2"
first_name = "Docker"
last_name = "Python"
if name == first_name and first_name == last_name:
  print("Demo of using and operator in conditional statement")

OR

The OR keywords check if any of the conditions evaluated are true.

name = "EC2"
first_name = "Docker"
last_name = "Python"
if name == first_name or first_name == last_name:
  print("Demo of using and operator in conditional statement")

NOT

The NOT keyword negates the outcome of the condition. For example, age_1 is indeed greater than age_2 but the not keyword turns it to false thereby skipping the next indented line(s) of action.

age_1 = 20
age_2 = 15
if not age_1 > age_2:
  print(f'{age_1} is greater than {age_2}')

PASS

To skip the execution of the supposed indented line. The pass keyword is not commonly used. If a condition is optional then there's no need to add it to the code.

bob_age = 19
doe_age = 22

if doe_age == bob_age:
  pass
print("true or false the expected outcome or next line of action was skipped")

#true or false the expected outcome or next line of action was skipped

Else

Else in programming is the same as it is in real-life situations. For example, When a child is sent to the shopping mall to get a chocolate biscuit there could be a condition like if there's no chocolate biscuit get oat biscuit. This can be achieved when writing a program by using the else keyword in Python.

biscuit = "milk"
if biscuit == "chocolate":
    print("Buy " + biscuit)
else:
    print("Buy oat biscuit" )
#Buy oat biscuit

Shorthand if..else

name = "Baja"
print(name) if name == "Alems" else print("Baja")

ELIF

There are use cases where there's a need to have multiple conditions to be met before ending it with an else command. Let's use the biscuit example to explain the use of elif. Hey Rob, go get a chocolate biscuit at the mall if there isn't one, check if they've got an oat biscuit and get one else return home with the money.

The elif can be used to define the conditions that happen when the first condition is not satisfied.

biscuit = "strawberry"
if biscuit == "chocolate":
    print("Buy " + biscuit)
elif biscuit == "oat":
    print("Buy oat biscuit")
else:
    print("Return home with the money")

#Return home with the money

Rob returns home with the money because none of the conditions was satisfied. In some programming languages, it is written as else if.

Nested Conditions using IF...ELIF..ELSE

Conditions can be nested when the checks are at different levels.

if 2 > 4:
    print("here")
else:
    if 3 < 4:
        print("nested if")
    elif 3 > 7:
        print("nested elif")
    else:
        print("nested else")
# nested if

Ensure to stick with best practices when writing conditional statements in Python programming to avoid having if..elif.else all over the codes. For example, the code in the nested section can be written in this form or even better than this with the same output.

print("here") if 2 > 4 else print("nested if") if 3 < 4 or 3 > 7 else print("nested else")
#nested if

Conclusion

Conditional Statements in Python are pretty easy to define using the if...elif...else keyword. Some functionalities in an application are dependent on the satisfaction of the defined conditions. It is essential to have this skill because almost every application small or large has several conditions to be satisfied to enable access or proper functionalities. Worthy of note is to always cross-check the conditions and ensure the next line action indentation is properly defined.

If you're looking forward to developing applications in Python using the OOP (Object-oriented programming), the major concepts are simplified on my blog here.

Find this helpful or resourceful?? kindly share and feel free to use the comment section for questions, answers, and contributions.

💡
Hashnode: Alemsbaja X: Alemsbaja | Youtube: Tech with Alemsbaja to stay updated on more articles

Did you find this article valuable?

Support Alemoh Rapheal Baja by becoming a sponsor. Any amount is appreciated!