Skip to Content
BonicBot A2DevelopmentPython ProgrammingLesson 5 - Conditional Logic

Lesson 5 - Conditional Logic

Learning Objective

Branch a program’s behavior using if / elif / else, and combine conditions with comparison and logical operators.


Introduction

So far every program you’ve written has run the same way every time.

Conditionals change that.

They allow a program to make decisions and take different actions depending on data. This is one of the most important concepts in programming because it enables programs to react to users, sensors, files, network responses, and countless other sources of information.

In this lesson, you’ll learn:

  • if, elif, and else
  • Comparison operators (<, >, <=, >=, ==, !=)
  • Logical operators (and, or, not)
  • How Python chooses which branch to execute

Comparison Operators


Logical Operators

Logical operators combine multiple conditions into a single decision.


Code

# conditionals.py score = 82 if score >= 90: grade = "A" elif score >= 75: grade = "B" elif score >= 60: grade = "C" else: grade = "F" print(f"Score: {score} -> Grade: {grade}") # Comparison and logical operators temperature_c = 5 is_raining = True if temperature_c < 10 and is_raining: print("Wear a warm, waterproof jacket.") elif temperature_c < 10: print("Wear a warm jacket.") elif is_raining: print("Bring an umbrella.") else: print("No jacket needed.")

Expected Output

Click to see expected output

Score: 82 -> Grade: B Wear a warm, waterproof jacket.

Understanding if / elif / else

A conditional chain lets your program choose between multiple paths.

score = 82 if score >= 90: grade = "A" elif score >= 75: grade = "B" elif score >= 60: grade = "C" else: grade = "F"

Python evaluates each condition from top to bottom.

For score = 82:

score >= 90

is false.

Next:

score >= 75

is true.

Python executes that branch and skips the rest.

Result:

Grade: B

Combining Conditions

You can combine conditions using and and or.

Example:

temperature_c = 5 is_raining = True if temperature_c < 10 and is_raining: print("Wear a warm, waterproof jacket.")

Both conditions are true:

temperature_c < 10

and

is_raining

So the message is printed.


Decision Flow Example

temperature_c = 5 is_raining = True

Python evaluates:

temperature_c < 10 and is_raining

Result:

True and True

which becomes:

True

Therefore:

Wear a warm, waterproof jacket.

🔧 Under the Hood

How does Python decide which branch to run?

An if / elif / else chain is checked from top to bottom.

The first condition that evaluates to True wins.

Every branch after it is skipped, even if later conditions would also be true.

For example:

score = 95 if score >= 90: print("A") elif score >= 75: print("B")

The second condition is never checked because the first one already succeeded.

Short-Circuit Evaluation

Python’s logical operators use short-circuit evaluation.

For and:

False and something

Python already knows the result must be False, so it skips evaluating something.

For or:

True or something

Python already knows the result must be True, so it skips evaluating something.

Example:

x = 0 if x != 0 and 10 / x > 1: print("Safe")

Since:

x != 0

is false, Python never evaluates:

10 / x

which prevents a division-by-zero error.


Student Challenge

Challenge 1

Write a Rock-Paper-Scissors judge.

Given:

player_1 = "rock" player_2 = "scissors"

Determine who wins without writing out all nine possible combinations.

Hint

You only need to check the three ways Player 1 can win.

If the game is not a tie and Player 1 didn’t win, then Player 2 must have won.


Click to see solution

# rps_judge.py player_1 = "rock" player_2 = "scissors" if player_1 == player_2: print("It's a tie!") elif ( (player_1 == "rock" and player_2 == "scissors") or (player_1 == "scissors" and player_2 == "paper") or (player_1 == "paper" and player_2 == "rock") ): print("Player 1 wins!") else: print("Player 2 wins!")

Challenge 2

Connect to your BonicBot and use its live battery level to decide how it should move.

Extend it:

Add a check using:

bot.get_min_obstacle_distance()

If it returns a value under 0.3 meters, call:

bot.stop()

immediately, regardless of what the battery check decided.

Full method details are available in the Python SDK reference.

Hint

get_min_obstacle_distance() can return:

None

if no scan has arrived yet.

Check for None before comparing it to a number.

Click to see solution

# challenge_battery_check.py from bonicbot_bridge import BonicBot with BonicBot(host='192.168.0.188') as bot: bot.wait_for_data(timeout=3.0) battery = bot.get_battery() distance = bot.get_min_obstacle_distance() print(f"Battery: {battery}%") if distance is not None and distance < 0.3: print(f"Obstacle at {distance:.2f} m — stopping immediately!") bot.stop() elif battery < 20: print("Battery low — staying put.") bot.stop() elif battery < 50: print("Battery moderate — moving cautiously.") bot.move_forward(speed=0.15, duration=1.0) else: print("Battery healthy — moving at normal speed.") bot.move_forward(speed=0.3, duration=1.0)

Reflection Question

In Challenge 2, the obstacle check needs to override the battery decision no matter which battery branch ran. Where would you place that obstacle check — inside each branch, or after the whole if / elif / else block — and why does that placement matter?


By the end of this lesson, you should be able to use comparison operators, combine conditions with logical operators, build decision trees with if / elif / else, and understand how Python evaluates conditions and chooses execution paths.

Last updated on