Logical Operators

Introduction:

  • Logical operators in Python are used to combine conditional statements and return a Boolean result (True or False).

Python Program:

  • Below is a Python program that takes boolean values in a and b, and performs logical operations on these values.

    python
    a = 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:
  1. and:
    • Returns True if both statements are true.
    • Example: x < 5 and x < 10
  2. or:
    • Returns True if one of the statements is true.
    • Example: x < 5 or x < 4
  3. not:
    • Reverses the result; returns False if the result is true.
    • Example: not(x < 5 and x < 10)

Exercises:

  1. 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))
      
  2. 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).

      python
      age = 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!