Python From Scratch
Python Booleans & Python Operators
Lesson 5 Content
Python Booleans
• Boolean Values
• Evaluate Values and Variables
• Most Values are True
• Some Values are False
• Functions can Return a Boolean
• Python - Booleans Exercises
Python Operators
• Python Arithmetic Operators
• Python Assignment Operators
• Python Comparison Operators
• Python Logical Operators
• Python Identity Operators
• Python Membership Operators
• Python Bitwise Operators
Python Booleans
Booleans represent one of two values: True or False.
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
print(10 > 9)
print(10 == 9)
print(10 < 9)
When you run a condition in an if statement, Python returns True or False:
Example
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")
Evaluate Values and Variables
The bool() function allows you to evaluate any value, and give you True or False in return,
Example
Evaluate a string and a number: Evaluate two variables:
x = "Hello"
print(bool("Hello"))
y = 15
print(bool(15))
print(bool(x))
print(bool(y))
Most Values are True
Almost any value is evaluated to True if it has some
sort of content. Example
Any string is True, except empty strings. The following will return True:
Any number is True, except 0.
bool("abc")
Any list, tuple, set, and dictionary are True, except
bool(123)
empty ones.
bool(["apple", "cherry", "banana"])
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 One more value, or object in this case, evaluates
The following will return False: to False, and that is if you have an object that is made
from a class with a __len__ function that
bool(False)
returns 0 or False:
bool(None)
Example
bool(0)
class myclass():
bool("")
def __len__(self):
bool(())
return 0
bool([]) myobj = myclass()
bool({}) print(bool(myobj))
Functions can Return a Boolean
You can create functions that returns a You can execute code based on the Boolean answer
Boolean Value: of a function:
Example
Example
Print "YES!" if the function returns True,
Print the answer of a function: otherwise print "NO!":
def myFunction() :
def myFunction() :
return True
return True
if myFunction():
print(myFunction()) print("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
Check if an object is an integer or not:
x = 200
print(isinstance(x, int))
Exercise:
The statement below would print a Boolean value, which one?
print(10 > 9)
Python Operators
Operators are used to perform operations on variables and values.
In the example below, we use the + operator to add together two values:
Example : print(10 + 5)
Python divides the operators in the following groups:
• Arithmetic operators
• Assignment operators
• Comparison operators
• Logical operators
• Identity operators
• Membership operators
• Bitwise operators
Python Arithmetic Operators Python Assignment Operators
Arithmetic operators are used with numeric values Assignment operators are used to assign
to perform common mathematical operations: values to variables:
Operator Name Example Operator Example Same As
+ Addition x+y = x=5 x=5
- Subtraction x-y += x += 3 x=x+3
* Multiplication x*y
-= x -= 3 x=x-3
/ Division x/y
*= x *= 3 x=x*3
% Modulus x%y
/= x /= 3 x=x/3
** Exponentiation x ** y
%= x %= 3 x=x%3
// Floor division x // y
//= x //= 3 x = x // 3
Python Arithmetic Operators
Arithmetic operators are used with numeric values **= x **= 3 x = x ** 3
to perform common mathematical operations: &= x &= 3 x=x&3
Operator Name Example |= x |= 3 x=x|3
== Equal x == y
^= x ^= 3 x=x^3
!= Not equal x != y
>>= x >>= 3 x = x >> 3
> Greater than x>y
<<= x <<= 3 x = x << 3
< Less than x<y
>= Greater than or equal to x >= y
<= Less than or equal to x <= y
Python Comparison Operators Python Logical Operators
Comparison operators are used to compare Logical operators are used to combine conditional
two values: statements:
Operator Name Example Operator Description Example
== Equal x == y and Returns True if both x < 5 and x < 10
statements are true
!= Not equal x != y
or Returns True if one x < 5 or x < 4
> Greater than x>y of the statements is
true
< Less than x<y
not Reverse the result, not(x < 5 and x < 10)
>= Greater than x >= y returns False if the
or equal to result is true
<= Less than or x <= y
equal to
Python Identity Operators
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
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
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