LOGICAL OPERATORS

‘If’ statements provide an excellent way to do certain things under certain conditions, however sometimes more complex conditions are required to accomplish the desired goal. Logical operators, sometimes called boolean operators, evaluate expressions and decide what boolean should be expressed from the evaluation. The name “boolean operators” is appropriate as the operators take boolean expression(s) – combinations of symbols which represent boolean (true or false) values – and evaluate these into a single boolean expression. If you don’t quite understand what I’m talking about here, don’t worry about it, it’s probably because I’m having to jump around the point a little bit while generalizing about these operators – let’s jump right in.

and

The “and” operator in Pyton is represented by the word and (how easy is that!). It takes the boolean value on the left of the operator and the boolean value on the right of the operator, and returns true if both are true, and false in all other conditions. From this, you can see that it behaves much like the word “and” does in the English language – if condition A and condition B are true, then the expression will be true, otherwise the expression will be false. This means that true and true will evaluate to true, and true and false will evaluate to false — both conditions must be true for the expression to be true.

Following on from the concept demonstrated above, the regular ol’ conditions that we’ve been using in if-statements end up evaluating to boolean values – being true if the condition is true, and false if it is not. This means that we can put a condition at each side of the && operator, and the full expression will only return true if the first condition and the second condition are true. An example of this is as follows:

[python]
age=int(input("Please enter your age: "))
if(age >= 35 and age <= 80):
print("You’re between 35 and 80 and can save money on your car insurance!")
else
print("Sorry, we don’t have any deals for you today!")
[/python]

or

The “or” operator behaves much like “and”, however only one of the two conditions has to be true. It is represented by the word or (do you see a pattern here?), and behaves much like the word “or” in the English language – if one condition or the other is true. This means that true or true, true or false, and false or true will all return true, and false or false will return false. This functionality, once again, is best seen in a code snippet in which a complex condition can be given to an ‘if’ statement:

[python]
age=int(input("Please enter your age: "))
if(age < 0 or age > 160):
print("You’re lying – you CANNOT be that age.")
else:
print("Thanks for inputting your age!")
[/python]

not

The “not” operator is a little different to “and” and “or”. It can only be prefixed to single expressions and essentially just inverts the boolean value of an expression. If the value is true, “not” will flick it to false – the “not” operator is expressed by the word not (I’m loving how easy this is), and hence not(true) is false, and not(false) is true. The functionality of the “not” operator can almost always be accomplished via different means, for example not(age > 5) could be expressed as age <= 5, however “not” really shines with readability, more complex expressions, and boolean variables. Take, for example, the following, which uses the “not” operator to create a neater condition:

[python]
want_to_start = int(input("Do you want to start the application?\n[0: No]\n[1: Yes]: "))
#An input of 0 is ‘false’, and 1 is ‘true’

print(bool(want_to_start)) #Have a look at what the value has become in boolean form

if(not(want_to_start)):
print("Then why open the application? Too bad, I’m starting anyway.")

print("Application starting.")
#Continue main program code here
[/python]

You Try

Copy the code above and execute it. Does it create the result you expected? Try changing it up to see what output is created.

Check Your Understanding

Before moving to the next section, let’s see how well you know the current material. Complete the tasks listed below and save your file as YourName_LogicalPractice.py.

  1. What are the logical operators and how do they work?
  2. Take each of these logic problems and write what you think the answer will be. In each case it will be either True or False. Once you have the answers written down, you will start Python in your Terminal and type each logic problem in to confirm your answers.
    • True and True
    • False and True
    • 1 == 1 and 2 == 1
    • “test” == “test”
    • 1 == 1 or 2 != 1
    • True and 1 == 1
    • False and 0 != 0
    • True or 1 == 1
    • “test” == “testing”
    • 1 != 0 and 2 == 1
    • “test” != “testing”
    • “test” == 1
    • not (True and False)
    • not (1 == 1 and 0 != 1)
    • not (10 == 1 or 1000 == 1000)
    • not (1 != 10 or 3 == 4)
    • not (“testing” == “testing” and “Zed” == “Cool Guy”)
    • 1 == 1 and (not (“testing” == 1 or 1 == 0))
    • “chunky” == “bacon” and (not (3 == 4 or 3 == 3))
    • 3 == 3 and (not (“testing” == “testing” or “Python” == “Fun”))
  3. Create a program that will read hour from the user (in a 24-hour clock format) and will output whether it is AM or PM. Use the logical operators shown above.Ex:
    Please enter an hour (from 1-24): 23
    This is 11pm
  4. Create a program that will allow a user to login in once they use the correct username and login. See below for a sample program. User entry is bolded.What is your user name? Merivale
    What is the password? Marauders
    Login Successful!
  5. Create a program that will allow the user to guess the capital of Canada. Your program should allow for uppercase and lowercase answers.See below for a sample program.
    User entry is bolded.
    ——-Your program will not have to loop. Each example below is a separate execution of the program.——-
    What is the capital of Canada?: Toronto
    Incorrect!
    What is the capital of Canada?: OTTAWA
    Correct!
    What is the capital of Canada?: ottawa
    Correct!
  6. Using logical opertators, create a program that will allow the user to enter any value EXCEPT 5.Example:
    Please enter an integer other than 5: 5
    Seriously? What don’t you ever listen to me?!