In this tutorial we are going to learn :

  • Logical Operators
  • And Operator
  • Or Operator
  • Not Operator
  • Chaining Comparison
  • Operators

 

 

Logical Operators

 

In Python, we use some logical operators to combine conditional statements. These
are :

  • and : Returns True if both statements are true
  • or : Returns True if either of statements is true
  • not : Returns True if statement is false

 

 

 

And Operator

 

And operator returns True if both statements are true.

Example :

In this program, If the weather is the weather is rainy and cold, the program is going to print  “Don’t go outside. ”  and otherwise the program will print ” You can go outside.

  • We set rainy_weather and cold_weather True
  • Both statements are True, the and operator is going to run.
rainy_weather = True
cold_weather = True
emergency = True

if rainy_weather and cold_weather:
    print("Don't go outside ")
    
else:
    print("You can go outside. ")
print("Done.") 

 

In the same program :

  • Let’s set rainy_weather False and cold_weather True.
  • One of the statements is False. the and operator is not going to run.
rainy_weather = False
cold_weather = True
emergency = True

if rainy_weather and cold_weather:
    print("Don't go outside ")
    
else:
    print("You can go outside. ")
print("Done.") 

 

 

 

Or Operator

 

Or operator returns True if either of statements is true.

Example :

In this same program, we used or operator instead of and operator.
rainy_weather is False and cold_weather is True. One of the statements is True
so or operator is going to run.

rainy_weather = False
cold_weather = True
emergency = True

if rainy_weather or cold_weather:
    print("Don't go outside ")
    
else:
    print("You can go outside. ")
print("Done.") 

 

 

 

Not Operator

 

Not operator returns True, the if statement is false.

Example :

In the same program, we used and , or , not operators together.

  • All variables are True.
  • emergency is True but we set it with not operator then and operator. So if

statement is not going to run.

rainy_weather = True
cold_weather = True
emergency = True

if ()rainy_weather or cold_weather) and not emergency:
    print("Don't go outside ")
    
else:
    print("You can go outside. ")
print("Done.") 

 

 

 

Chaining Comparison Operators

 

Example :

We don’t need to use and operator like this :


We have a better way to do this :

age = 23

if 18 <= age < 60:
    print("Approved. ") 
0 0 vote
Article Rating
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments