Python If Elif Else
Conditional Statements and Logical Operators in Python
Use if
, elif
, and else
to control the flow of your program based on conditions.
You can write nested conditions (conditions inside other conditions) for more complex logic.
Python supports comparison operators (like ==
, !=
, <
, >
, <=
, >=
) to compare values.
You can combine conditions using logical operators such as and
, or
, and not
.
Â
Example 1
batting_average = 0.333
Here we check if the battling_average is greater than or equal to 0.300.
if the condition is true, it prints “All-Star-level”.
we use if statement when we want to run a block of code only if a condition is met.
if batting_average >= 0.300: print("All-Star-level")

batting_average = 0.2
This checks if batting_average is 0.300 or higher.
if true, it prints “All-Star-level” otherwise , it prints “Not All-Star-level”
The else block provides an alternative action when the condition is false.Â
This ensures that one of the teo messahes will always be printed.
if batting_average >= 0.300: print("All-Star-level") else: print("Not All-Star-level")

batting_average = 0.25
This code uses multiple conditions to classify a player based on batting average:
>= 0.300
: All-Star-level
>= 0.26
: Decent Player
Between 0.22
and 0.26
: AVG Player
Below 0.22
: Below AVG
Â
we use the elif when we have multiple specific ranges or categories to evaluate, making.
if batting_average >= 0.300: print("All-Star-level") elif batting_average >= 0.26: print("Decent Player") elif 0.26 > batting_average >= 0.22: print("AVG Player") else: print("Below AVG")

Example 2 Multiple Conditions and multiple elifs
hits = 200 home_runs = 35
Here, we use logical opertors like and we also use multiple elif.
The use of “and” allows us to check for multiple conditions at once.
if hits > 150 and home_runs > 25: print("Great all-around player") elif hits > 150: print("Great hitter") elif home_runs > 25: print("Power hitter") else: print("Average player")

Example 3 True Conditions (or)
fast_runner = True outs = 2 balls = 3 strikes = 2
Here we check if a player is a fast_runner or if the count is 2 outs, 3 balls and 2 strikes.
if eitjer condition is true, it prints “Can Steal Base”.
Otherwise, it prints “don’t steal”.
This is an example of using combined logical operators (or).
if fast_runner or (outs == 2 and balls == 3 and strikes == 2): print("Can Steal Base") else: print("don't steal")

Example 4 NOT ,!=
Here we check if the player is not a fast runner or the situation does not match a specific condition.
if eiter of those is true, the advice is “don’t steal”
Otherwise, it prints “Can Steal Base”.
This example shows how not and != can be used to reverse conditions, allowing us to specify when not to perform an action based on multiple checks.
if not fast_runner or (outs != 2 and balls != 3 and strikes != 2): print("don't steal") else: print("Can Steal Base")

Example 5 Nested Conditions
runs_scored = 7 innings_played = 9
Explanation:
This code first checks if the game has gone 9 innings (i.e., is complete).
If it is, it then checks the number of runs scored to classify the game as high or moderate scoring.
If the game hasn’t reached 9 innings, it prints "Game is not complete"
.
Nested conditions allow you to perform secondary checks only if a primary condition is met—useful when decisions depend on multiple layers of logic.
if innings_played == 9: if runs_scored >= 6: print("High scoring game") else: print("Moderate scoring game") else: print("Game is not complete")

Example 6 - Advanced, you can skip if you are a beginner
The is
operator in Python is used to compare the identity of two objects, that is, it checks whether both operands refer to the exact same object in memory.
This is different from the ==
operator, which checks whether the values of the objects are equal, even if they are different objects.
team_list = ["Yankees", "Red Sox", "Dodgers", "Cubs", "Rays"]
team_a = team_list[0] # "Yankees"
team_b = team_list[0] # "Yankees"
Here we check whether team_a
and team_b
refer to the same object in memory. Since both reference the first element in team_list
, they are the same object, so it prints "Yes - same object in memory"
.
The “is” operator is useful when you want to verfiy if two variables point to the exact same object, which is different from comparing their values with ==
if team_a is team_b: print("Yes - same object in memory") else: print("Not Same object in memory")

if team_a == team_b: print("team_a and team_b have the same team name")

Example 7 NONE ,dictionaries
player_stats = { "player1": {"name": "John", "hits": 120, "home_runs": 30}, "player2": {"name": "Alex", "hits": None, "home_runs": 20}, "player3": {"name": "Sam", "hits": 90, "home_runs": None} }
This code loops through a dictionary of players and their stats, checking if the hits
or home_runs
values are None
(meaning data is missing). If so, it prints a message saying statistics are not available; otherwise, it prints the actual numbers
Â
None is used in Python to represent missing or undefined data. THis pattern is common when dealing with incomplete datasets, allowing for safe checks before accessing values.
Also, player_stats is a dictionary where each key (like “player1”) maps to another dictionary holding that player’s stats. This nested dictionary structure is useful for organizing complex data hierarchically.
Dictionaries provide fast lookup, insertion, and deletion of data based on keys, making them ideal for representing structured data such as records, configurations, or JSON-like data.
for player, stats in player_stats.items(): if stats["hits"] is None: print(f"{stats['name']} does not have hit statistics available.") else: print(f"{stats['name']} has {stats['hits']} hits.") if stats["home_runs"] is None: print(f"{stats['name']} does not have home run statistics available.") else: print(f"{stats['name']} has {stats['home_runs']} home runs.")

Example 8 Ternary expression
retired_years = 5
Ternary expressions help make our code shorter and more readable when we need to choose between two values based on a condition.
Here we assign “Eligable” to message if “retired_years is” 5 or more, otherwise it assigns “Not Eligible”.
It is a compact way to write simple if-else statements in a single line.
message = "Eligable" if retired_years >= 5 else "Not Eligable"
Ryan is a Data Scientist at a fintech company, where he focuses on fraud prevention in underwriting and risk. Before that, he worked as a Data Analyst at a tax software company. He holds a degree in Electrical Engineering from UCF.