Python - tutorial - 03/14

booleans - operators

Revision:


Python - booleans

Boolean values: in programming you often need to know if an expression is "True" or "False".You can evaluate any expression in Python, and get one of two answers, True or False. When you compare two values, the expression is evaluated and Python returns the Boolean answer.

Example 1: compare two values

        print(10 > 9) # True
        print(10 == 9) # False
        print(10 < 9) # False
    

When you run a condition in an if statement, Python returns "True" or "False".

Example 2: print a message based on whether the condition is True or False:

        a = 200
        b = 33
        if b > a:
          print("b is greater than a")
        else:
          print("b is not greater than a") # b is not greater than a 
    

Evaluate values and variables: the bool() function allows you to evaluate any value, and give you "True" or "False" in return.

Example 3: evaluate a string and a number:

        print(bool("Hello")) # True
        print(bool(15))  # True
    

Example 4: evaluate two variables:

        x = "Hello"
        y = 15
        print(bool(x)) # True
        print(bool(y)) # True
    

Most values are True: almost any value is evaluated to "True" if it has some sort of content.

Any string is "True", except empty strings.
Any number is "True", except 0.
Any list, tuple, set, and dictionary are "True", except empty ones.

Example 5: the following will return True:

        bool("abc") # True
        bool(123) # True
        bool(["apple", "cherry", "banana"]) # True
    

Some values are False: in fact, there are not many values that evaluate to "False", except empty values, such as (), [], {}, "", the number 0, and the value None. And of course the value False evaluates to "False".

Example 6: the following will return False:

        bool(False)
        bool(None)
        bool(0)
        bool("")
        bool(())
        bool([])
        bool({})
    

One more value, or object in this case, evaluates to "False", and that is if you have an object that is made from a class with a __len__ function that returns 0 or False.

Functions can return a Boolean: you can create functions that returns a Boolean value.

Example 7: print the answer of a function:

        def myFunction():
            return True
        print(myFunction()) # True
    

You can execute code based on the Boolean answer of a function.

Example 8: print "YES!" if the function returns True, otherwise print "NO!":

        def myFunction() :
            return True
        if myFunction():
            print("YES!") # YES!
      else:
            print("NO!")
    

Python also has many built-in functions that return a boolean value, like the isinstance() function, which can be used to determine if an object is of a certain data type.

Example 9: check if an object is an integer or not:

        x = 200
        print(isinstance(x, int)) # True
    


Python - operators

Python operators are divided in the following groups:

a/ arithmetic operators,
b/ assignment operators,
c/ comparison operators,
d/ logical operators,
e/ identity operators,
f/ membership operators,
g/ bitwise operators.

Python arthmetic operators are used with numeric values to perform common mathematical operations.

Operator - Name - Example
+ : addition - x + y
- : subtraction - x - y
* : multiplication - x * y
/ : division - x / y
% : modulus - x % y
** : exponentiation - x ** y
// : floor division - x // y

Python assignment operators are used to assign values to variables.

Operator - Example - Same as
= : x = 5 - x = 5
+= : x += 3 - x = x + 3
-= : x -= 3 - x = x - 3
*= : x *= 3 - x = x * 3
/= : x /= 3 - x = x / 3
%= : x %= 3 - x = x % 3
//= : x //= 3 - x = x // 3
**= : x **= 3 - x = x ** 3
&= : x &= 3 - x = x & 3
|= : x |= 3 - x = x | 3
^= : x ^= 3 - x = x ^ 3
>>= : x >>= 3 - x = x >> 3
<<= : x <<= 3 - x = x << 3

Python comparison operators are used to compare two values.

Operator - Name - Example
== : Equal - x == y
!= : Not equal - x != y
> : Greater than - x > y
< : Less than - x < y
>= : Greater than or equal to - x >= y
<= : Less than or equal to - x <= y

Python logical operators are used to combine conditional statements.

Operator - description - Example
and : Returns True if both statements are true - x < 5 and x < 10
or : Returns True if one of the statements is true - x < 5 or x < 4
not : Reverse the result, returns False if the result is true - not(x < 5 and x < 10)

Python identity operators are used to compare the objects, not if they are equal, but if they are actually the same object, with the same memory location.

Operator - Description - Example
is : Returns True if both variables are the same object - x is y
is not : Returns True if both variables are not the same object - x is not y

Python membership operators are used to test if a sequence is presented in an object.

Operator - Description - Example
in : Returns True if a sequence with the specified value is present in the object - x in y
not in : Returns True if a sequence with the specified value is not present in the object - x not in y

Python bitwise operators are used to compare (binary) numbers.

Operator - Name - Description
& : AND - Sets each bit to 1 if both bits are 1
| : OR - Sets each bit to 1 if one of two bits is 1
^ : XOR - Sets each bit to 1 if only one of two bits is 1
~ : NOT - Inverts all the bits
<< : Zero fill left shift - Shift left by pushing zeros in from the right and let the leftmost bits fall off
>> : Signed right shift - Shift right by pushing copies of the leftmost bit in from the left, and let the rightmost bits fall off