Table of Contents
Logical operators in Python - and
, or
, and not
- are essential tools for writing flexible and powerful conditional logic. These operators
let you combine multiple Boolean expressions and control program behavior based on more than one condition. From form validation to decision-making in games or user access
control, mastering logical operators opens the door to building smarter and more dynamic programs. This practice set is designed to help you understand how these operators
behave, how to structure compound conditionals, and how to avoid common logical pitfalls.
To solve the following problems, you should be familiar with these foundational topics:
- Logical Operators in Python
- Comparison Operators
- Boolean Type
- Variables
- Basic
if
/elif
/else
syntax - Using
input()
andprint()
for user interaction
Beginner-Level Practice – Logical Operators
Beginner-level tasks focus on understanding how and
, or
, and not
work in simple expressions. You’ll use them to combine conditions and
control the flow of basic user input scenarios. These exercises are designed to help you gain confidence in reading and writing compound logical statements, evaluating multiple
criteria, and handling true/false logic in practical ways.
Task 1: Simple Access Checker
Write a Python program that checks if a user can enter a restricted area. The conditions are: the user must be at least 18 years old and must have a valid ticket (entered as "yes" or "no"). Ask for both inputs and use logical operators to decide access. Print an appropriate message based on the result.
What this Task Teaches
This task teaches how to evaluate two separate conditions using the and
operator and control flow using if
/else
. You'll understand how
logical operators enforce multiple constraints and how user input affects outcomes.
- Using the
and
operator to combine requirements - Understanding Boolean evaluation of input
- Basic decision-making with
if
/else
- Controlling output based on combined conditions
Hints and Tips
Convert the age to an integer and check that it is 18 or more. Then check if the ticket input is exactly "yes"
. Use and
to combine both checks in one
condition.
- Use
input()
to collect age and ticket status - Convert the age to
int
before comparison - Use
ticket == "yes"
to check ticket validity - Use
and
to combine both checks
Common Mistakes
Many beginners forget to convert the age from a string to an integer, which causes comparison errors. Others may type "Yes" with a capital letter and expect it to match "yes".
It’s also common to confuse and
with or
, which changes the logic entirely and leads to incorrect access permissions.
- String comparison without type conversion: Trying to compare a string number to an integer without using
int()
will cause logic errors. - Case sensitivity in text inputs:
"Yes"
and"yes"
are not the same in Python. -
Incorrect use of
or
instead ofand
: This may allow people to pass even if one condition fails. - Reversed logic in output messages: Be careful which block your
print()
belongs to. - No validation for input format: Failing to prompt the user correctly may result in unexpected inputs like "maybe".
Step-by-Step Thinking
Think about access like a security guard. The person must be old enough and have a valid ticket. You must evaluate both conditions and only allow access if both are satisfied.
- Ask the user for their age and convert it to an integer
- Ask if the user has a valid ticket
- Check if the age is at least 18 and the ticket input is "yes"
- If both are true, print "Access granted"
- Otherwise, print "Access denied"
How to Make it Harder
You can expand this program by adding more checks such as membership status, time of day, or even introducing a guest list. This allows you to experiment with more complex logic structures.
- Add a check for VIP status and allow access even if the ticket is missing
- Ask for the current hour and restrict entry after midnight
- Add a guest list and verify that the entered name is present in it
- Print different messages based on which condition failed
Task 2: Free Shipping Checker
Write a Python program for an online store that checks if a customer qualifies for free shipping. The conditions are: the order total must be at least $50 or the customer must be a premium member. Ask the user to enter their order amount and whether they are a premium member ("yes" or "no"). Then print whether they get free shipping or not.
What this Task Teaches
This task helps you understand how to use the or
operator to evaluate alternate eligibility criteria. You’ll learn to check numeric and string values together, and
apply flexible logic that lets the user qualify by meeting either of two conditions. It also encourages precise conditional structuring and good user messaging practices.
- Working with mixed condition types (numeric and string)
- Using the
or
operator to allow multiple valid paths - Branching logic with
if
/else
- Clean output formatting for user-friendly results
Hints and Tips
Ask the user for two inputs: total order amount (as a float or integer) and membership status. Use or
to check whether either condition is met, and remember to
handle case sensitivity for user input.
- Use
float(input())
orint(input())
for price - Use
lower()
to simplify membership check - Check if total is ≥ 50 or membership is
"yes"
- Print "Free shipping!" if either condition is true
Common Mistakes
A frequent mistake is confusing or
with and
, which can cause the user to be unfairly denied free shipping. Another error is failing to convert the
total price to a numeric type before comparison. Also, beginners often forget to normalize user input (like upper/lowercase), causing logic to fail when checking text.
- Wrong operator used: Using
and
instead ofor
means both conditions must be met, which changes the intended logic completely. - Missing input conversion: Comparing strings like "40" to 50 without converting to
float
orint
will always fail. - Input case sensitivity: Checking
membership == "yes"
fails if the user types "Yes" or "YES". - Not validating both inputs: Failing to gather both conditions could lead to incomplete logic and wrong outcomes.
- Hardcoding logic: Relying only on one condition or hardcoding results breaks flexibility and real-life applicability.
Step-by-Step Thinking
You want your store to offer free shipping when either of two things is true. The customer can qualify by spending enough or by being a premium member. Your program should clearly check both and act accordingly.
- Ask the user for the order total
- Ask if they are a premium member ("yes" or "no")
- Convert the order total to a number
- Normalize membership input with
.lower()
- Check if total is ≥ 50 or membership is "yes"
- If yes, print "Free shipping!"
- Else, print "Shipping fee applies."
How to Make it Harder
You can improve this task by adding tiered benefits, such as discount thresholds or combining shipping and promo code logic. This helps you simulate a real-world shopping platform more accurately.
- Introduce promo codes for free shipping regardless of order total
- Add an
elif
branch that gives half-price shipping if total is between $30 and $49 - Track the number of orders a user places and give free shipping after 3 purchases
- Build a reusable function for shipping checks
Intermediate-Level Practice – Logical Operators
At the intermediate level, you'll apply logical operators to more nuanced real-world scenarios. These tasks involve more than just checking two user inputs. You’ll build
decision-making systems where multiple conditions interact, and the logic can be layered using combinations of and
, or
, and not
.
Understanding operator precedence and constructing clean, readable expressions becomes more important as your programs grow in complexity. These exercises will challenge your
ability to plan logic flows and anticipate all outcomes.
Task 1: Fitness App Goal Tracker
You're building a simple fitness tracking system. Ask the user if they’ve exercised today, eaten healthy, and slept at least 7 hours. If they’ve done at least two of the three activities, they earn a “Wellness Star”. Use logical operators to check these combined conditions and print a message that encourages or motivates them.
What this Task Teaches
This task teaches how to work with multiple Boolean inputs and apply logic to evaluate combined conditions. You’ll use and
, or
, and simple math to
determine how many “healthy habits” were achieved. It helps you reason about thresholds and build multi-condition evaluations.
- Using multiple
if
conditions withor
logic - Combining Boolean flags and simple counters
- Applying thresholds to decide outcomes
- Thinking logically across several related conditions
Hints and Tips
Store the answers to each question as Boolean values (like True
or False
) and then count how many are True
. If the total is 2 or more,
print that the user earns a Wellness Star.
- Normalize user input like "yes"/"no" using
.lower()
- Use variables to store
True
/False
values - Sum up the
True
values using simple arithmetic - Use
if total >= 2
to decide the result
Common Mistakes
A common issue is trying to write one giant if
statement with complex and
/or
logic, which often leads to incorrect grouping or precedence
errors. Beginners may also forget to convert text answers into Boolean values before performing calculations, which results in faulty logic.
- Misusing operator precedence: Not using parentheses correctly leads to unexpected outcomes when mixing
and
andor
. - Improper Boolean conversion: Using string values directly in conditions without converting to
True
/False
. - Counting logic errors: Forgetting to increment the count only when a condition is
True
. - Hardcoding responses: Skipping dynamic input and assuming fixed values reduces flexibility.
- Unclear user messages: Not informing the user what each input means can lead to confusion.
Step-by-Step Thinking
Think of this like a checklist. If the user did at least 2 good habits, they’re doing well. You need to gather responses, evaluate each one, and count how many are
True
.
- Ask the user three yes/no questions: exercise, healthy eating, and sleep
- Convert each answer into a Boolean value
- Add the number of
True
values - If the count is 2 or more, print a positive message
- Otherwise, offer encouragement for tomorrow
How to Make it Harder
Add more habits or different reward levels based on how many positive habits were done. You can also turn this into a full report with a rating system or feedback for each habit.
- Track 5–7 habits instead of 3
- Assign a score to each habit and calculate a total wellness score
- Provide personalized feedback based on which habits were skipped
- Use
elif
chains to create tiered results (bronze, silver, gold)
Task 2: Secure Login Filter
Build a login checker that asks for a username and password. Access should be granted only if both match the expected credentials and the user is not on a
blocked list (ask for “blocked” status as “yes”/”no”). Use and
and not
to evaluate the combination of inputs and give proper feedback.
What this Task Teaches
This task introduces how to use not
in combination with and
and equality checks to enforce multiple login conditions. You'll learn to verify secure
access, combine Boolean conditions, and add logic that excludes users based on a flag (blocked status).
- Matching user credentials using equality operators
- Using
not
to filter blocked users - Combining logic into one readable conditional
- Providing clear conditional feedback
Hints and Tips
Use three separate inputs: username, password, and block status. Convert block status to lowercase and use not (blocked == "yes")
as part of the condition to
ensure only unblocked users are allowed access.
- Use
input()
to get credentials and block status - Check that username and password both match
- Use
not
to ensure blocked users are denied access - Display an appropriate message based on result
Common Mistakes
It’s common to reverse the blocked logic and mistakenly grant access to blocked users. Also, many beginners forget to use parentheses around complex and
/not
expressions, resulting in incorrect outcomes.
-
Incorrect use of
not
: Placingnot
in the wrong place can completely reverse your logic. - Skipping parentheses: Mixing
and
andnot
without clear grouping leads to operator precedence issues. - Case sensitivity in credentials: Usernames like
"Admin"
vs"admin"
can fail due to exact match requirements. - Insecure hardcoded logic: Not verifying all three conditions can leave the system vulnerable.
- Feedback not clear: Not explaining why login was denied confuses users.
Step-by-Step Thinking
Think of the system like a bouncer at a club: the guest must be on the list (username/password) and not banned (blocked). If all checks pass, they’re in.
- Ask the user to input a username and password
- Ask if the user is blocked ("yes" or "no")
- Check if username and password match expected values
- Use
not blocked
to deny access if needed - Print “Login successful” or “Access denied”
How to Make it Harder
Extend the task into a real login flow with multiple users, password validation, and limited login attempts. You can also turn blocked status into a separate list.
- Read allowed users from a dictionary or list
- Simulate 3 login attempts before blocking the user
- Store blocked users in a list and check membership
- Track login attempts and time-based access rules
Advanced-Level Practice – Logical Operators
At the advanced level, you'll use logical operators in combination with nested conditions, dynamic user input, and real-world rule systems. These problems simulate scenarios such as access control, rule engines, and status evaluations in apps or systems. The tasks here test your ability to create concise yet readable logic, deal with multiple layers of decision-making, and refactor complex conditions into understandable steps. This is where true logic planning, condition optimization, and coding discipline come into play.
Task 1: Smart Thermostat Recommendation
You’re building logic for a smart thermostat that gives users a recommendation based on room temperature, humidity, and whether windows are open. Ask the user for:
- Room temperature (in °C)
- Humidity percentage
- Window status ("open" or "closed")
The system should recommend: "Turn on the AC" if the temperature is above 28 and humidity is above 60%, or if the windows are closed and temp is above 30.
What this Task Teaches
You will practice writing complex logical conditions that mix numerical thresholds and string values. This task helps you apply and
/or
/not
in an optimized decision-making context and shows how logical grouping controls program behavior. It also teaches you to convert messy requirements into manageable,
well-structured condition blocks.
- Working with multiple input types and values
- Designing nested and combined logical expressions
- Controlling program output based on system conditions
- Building readable condition trees with proper grouping
Hints and Tips
Break the condition into smaller logical groups. First, compare temperature and humidity. Then separately check if the window is closed and temperature is high. Use parentheses to manage operator precedence clearly.
- Convert temp and humidity to
float
- Normalize window input using
.lower()
- Use
if (temp > 28 and humidity > 60) or (temp > 30 and window == "closed")
- Output recommendation accordingly
Common Mistakes
Many learners forget to use parentheses in complex logical expressions, which leads to wrong evaluation order. Others mix up string inputs with numeric checks, or forget to
normalize text inputs. Improper logic nesting is a common pitfall when multiple or
and and
are combined.
- No parentheses: Without parentheses,
and
binds tighter thanor
, which often changes the meaning of your condition. - Forgetting float conversion: Comparing a string to a number will never work correctly.
- Unnormalized input: Not lowercasing "Open" or "Closed" leads to mismatches in condition checks.
- Overly complex condition chains: Writing all in one line without organizing into readable blocks creates bugs and poor maintainability.
- Inconsistent comparison logic: Switching from > to >= inconsistently changes system thresholds unexpectedly.
Step-by-Step Thinking
Start by identifying the key metrics: temperature, humidity, and window state. Use logic to break down both possible conditions under which AC should turn on.
- Ask the user for temperature (°C), humidity (%), and window status
- Convert numeric values using
float()
- Normalize window input with
.lower()
- Write one condition:
temp > 28 and humidity > 60
- Write second condition:
temp > 30 and window == "closed"
- Use
or
to combine the two logic branches - Display “Turn on AC” if condition is true; else, say “No need to adjust”
How to Make it Harder
You can enhance this logic by adding dynamic rules based on time of day, room occupancy, or electricity price. These additions simulate real smart home systems.
- Include a check for daytime/nighttime using user input
- Add a condition where price per kWh affects decision
- Introduce an override switch (“manual AC mode”)
- Build a function to encapsulate the logic and reuse it
Task 2: Online Exam Proctor Check
Build a small system for a remote exam platform that checks if a student’s test session is valid. It asks:
- Whether the webcam is on (
"yes"/"no"
) - Whether screen recording is active
- Whether background noise is detected
The session is considered valid only if the webcam and screen recording are on and there’s no background noise. Use logical operators to check this and print the outcome.
What this Task Teaches
You’ll build logic for rule validation across multiple simultaneous conditions. The exercise shows how to reject access when one key requirement fails even if the rest are
okay. You’ll combine and
with not
to build exclusion logic.
- Checking required flags for system compliance
- Using
not
to block based on violations - Validating a rule engine with multiple dependencies
- Writing a rejection reason that reflects the condition
Hints and Tips
Normalize all inputs, especially yes/no answers, and handle them consistently. Focus on building one compound condition that includes all three criteria with the proper
combination of and
and not
.
- Use
.lower()
on all input strings - Check if both webcam and screen are "yes"
- Ensure that background noise is not detected
- Use one compound
if
to handle all conditions together
Common Mistakes
Many beginners forget that not
applies to entire conditions, not just variables. Improper input normalization also results in failed condition checks. And logic
order matters - especially when prioritizing safety rules like background noise detection.
- Negating wrong condition:
not noise == "yes"
may not behave as intended - use parentheses or clear logic. - Typos in input: "Yes" vs "yes" fails if not normalized.
-
Wrong use of
and
vsor
: Swapping logic operators leads to letting unqualified students through. - Inverted logic: Accidentally allowing exams when
not webcam
is true. - Partial checks: Only verifying webcam or screen and forgetting the rest leaves vulnerabilities.
Step-by-Step Thinking
This system enforces a strict exam environment. All conditions must be satisfied simultaneously, so build one master if
expression that reflects that.
- Ask the user for webcam, screen recording, and background noise status
- Normalize all inputs to lowercase
- Use
webcam == "yes" and screen == "yes" and noise == "no"
- Display "Session valid" if all pass; else "Session flagged"
- Consider printing which rule failed for bonus clarity
How to Make it Harder
Make the check more robust by tracking time of detection, logging rule violations, or allowing one minor violation with a warning system.
- Allow 1 failed rule before rejection and show a warning
- Log failed input states and show a full audit report
- Assign severity levels to each rule
- Use a loop to repeat checks every 30 seconds