Logical Operators
Introduction:
- Logical operators in Python are used to combine conditional statements and return a Boolean result (
TrueorFalse).
Python Program:
Below is a Python program that takes boolean values in
aandb, and performs logical operations on these values.pythona = True b = False print('a and b :', (a and b)) print('a or b :', (a or b)) print(' not a :', (not a))
Output:
a and b : False
a or b : True
not a : False
Detailed Tutorials:
- Here are detailed tutorials covering each of the logical operators with examples:
- and:
- Returns
Trueif both statements are true. - Example:
x < 5 and x < 10
- Returns
- or:
- Returns
Trueif one of the statements is true. - Example:
x < 5 or x < 4
- Returns
- not:
- Reverses the result; returns
Falseif the result is true. - Example:
not(x < 5 and x < 10)
- Reverses the result; returns
Exercises:
- Basic Logical Operations:
Write a program to perform basic logical operations (
and,or,not) on two boolean values entered by the user.python# Read boolean values from user a = input("Enter first boolean value (True/False): ") b = input("Enter second boolean value (True/False): ") a = a == 'True' b = b == 'False' # Perform logical operations print('a and b :', (a and b)) print('a or b :', (a or b)) print(' not a :', (not a))
- Logical Conditions with User Input:
Write a program to check if a user is a teenager (age between 13 and 19) and if they have permission (boolean input).
pythonage = int(input("Enter age: ")) has_permission = input("Do you have permission (yes/no): ").lower() == 'yes' if age >= 13 and age <= 19 and has_permission: print("You are a teenager with permission.") else: print("You are either not a teenager or do not have permission.")
Summary:
- Logical operators in Python are crucial for combining conditions and making decisions in your programs. Practice using these operators to become proficient in writing conditional statements and logical expressions in Python!