Arunav Goswami
Data Science Consultant at almaBetter
Learn how to use logical operators in Python, including and, or, and not, with examples. Know more about their functions, precedence, and Pythonic applications
Python logical operators are essential for handling decision-making in programming. These operators evaluate expressions, returning a Boolean value (True or False) based on the logic defined. Python offers three main logical operators: and, or, and not, which allow developers to create complex conditions for controlling the flow of code.
In Python, logical operators work with Boolean values and are used in expressions to perform logic-based evaluations. The output of logical operations determines whether certain code blocks execute. Logical operators are pivotal in scenarios such as:
Logical operators follow Python’s syntactical conventions and apply rules for short-circuiting, which means evaluating only as far as necessary to determine an outcome.
Python supports three primary logical operators:
Each operator has distinct behavior in evaluating expressions.
The and operator returns True if both expressions are True; otherwise, it returns False. It follows a straightforward Boolean logic rule:
Usage of and
The and operator is commonly used in situations where multiple conditions must be met for code execution. For instance:
age = 25
income = 50000
if age > 18 and income > 30000:
print("Eligible for loan")
Explanation: Here, the program checks if age is greater than 18 and income is greater than 30000. If both conditions hold, it prints "Eligible for loan."
The or operator evaluates to True if at least one of the expressions is True. The following logical rules apply:
Usage of or
The or operator is ideal when any one of multiple conditions should result in a True outcome:
age = 17
income = 35000
if age > 18 or income > 30000:
print("Eligible for partial loan")
Explanation: Here, even though age is not greater than 18, the income meets the condition. Therefore, the program will output "Eligible for partial loan."
The not operator inverts the Boolean value of an expression. It changes True to False and vice versa:
Usage of not
The not operator is used when the requirement is to check for the negation of a condition:
is_student = False
if not is_student:
print("Eligible for membership discount")
Explanation: Here, is_student is False, so not is_student returns True, and the program outputs "Eligible for membership discount."
Operator | Description | Example Expression | Result | Explanation |
---|---|---|---|---|
and | Logical AND | True and True | True | Returns True only if both expressions are True. |
True and False | False | If any expression is False, the result is False. | ||
or | Logical OR | True or False | True | Returns True if at least one expression is True. |
False or False | False | Returns False only if both expressions are False. | ||
not | Logical NOT (negation) | not True | False | Inverts the Boolean value; True becomes False, and False becomes True. |
not False | True | Useful for checking the opposite of a condition. |
Logical operators are frequently used within conditional statements to control program flow.
Example of Combining Logical Operators
In complex conditions, logical operators can be combined for multiple evaluations:
age = 20
is_employed = True
has_bad_credit = False
if age > 18 and is_employed and not has_bad_credit:
print("Loan approved")
Explanation: Here, all three conditions must be met for "Loan approved" to be printed. If has_bad_credit were True, the not has_bad_credit would evaluate as False, causing the entire expression to return False.
Python has a specific order of evaluation for logical operators:
This order ensures that expressions are evaluated in a predictable manner. For instance:
result = True or False and not False
print(result) # Outputs: True
Explanation:
To alter the order of evaluation, parentheses can be used:
result = (True or False) and not False
print(result) # Outputs: True
Python uses short-circuit evaluation to optimize performance by stopping evaluation as soon as the result is determined:
def func1():
print("Function 1 executed")
return True
def func2():
print("Function 2 executed")
return False
print(func1() or func2()) # Only "Function 1 executed" is printed
Explanation: Since func1() returns True, func2() is not executed due to short-circuiting in the or operator.
username = "admin"
password = "12345"
if username == "admin" and password == "12345":
print("Login successful")
else:
print("Invalid credentials")
This example uses the and operator to check that both the username and password match expected values.
age = 16
is_student = True
if age < 18 or is_student:
print("Eligible for discount")
Here, the or operator checks if the user qualifies for a discount by either being under 18 or a student.
is_registered = False
if not is_registered:
print("User needs to register")
In this example, the not operator is used to ensure that unregistered users are prompted to register.
Logical operators Python are key to writing efficient and Pythonic code. By leveraging logical operators, Python developers can create concise, expressive code for various applications, such as filtering data, validating input, and handling exceptions.
# Verifying both variables have values
value1, value2 = 10, 20
if value1 and value2:
print("Both values are non-zero")
This code takes advantage of Python's truthy values, where non-zero numbers evaluate as True, simplifying the condition check.
Want to dive deeper into Python? Check out our comprehensive Python Cheat Sheet, experiment in our Online Python Compiler, or explore our complete Python Tutorial!
Logical operators in Python and, or, and not are fundamental in programming for controlling the flow of execution. These operators help developers build conditional logic, control loops, and write expressive code. Mastering logical operators is essential for writing clean, efficient, and optimized Python programs that can handle a variety of logic-based scenarios.
Ready to take your skills further? Enroll in our Data Science Course or pursue a Masters in Data Science to advance your career!
Related Articles
Top Tutorials