Logic

To start with, here is a list of the logical comparison operators provided by Python:

  • ==
    • 'is equal to'
  • !=
    • 'is not equal to'
  • >
    • 'is greater than'
  • >=
    • 'is greater than or equal to'
  • <
    • 'is less than'
  • <=
    • 'is less than or equal to'

In addition to these standard logical comparison operators, there are some natural language-derived ones:

  • in
    • 'contains'
  • not in
    • 'does not contain'

And each of the aforementioned operators can be combined with continuous logic:

  • and
  • or

All of which works in the tradional sense that logic works in high-level programming. Here are some examples.

a = 5
b = 5
c = (a == b)

c is equal to True, because a is equal to b.

Boolean logic can be used anywhere any other kind of valid expression can be used, but its most common usage is in if statements.

if c == True:
   print("c is True")

if c:
   print("c is True")

if (a == b) == c:
   print("c is True")

All of these are the same. If a variable is equal to True, there is no need to compare it to itself unless you would like to check for the inverse. Additionally, all values besides 0 and False are regarded as True in a conditional statement.

if c and a:
   print("c and a are True")

# Even though a is actually 5

if a and b:
   print("a and b are True")

# Even though a is 5 and b is 5

d = (0 or False or c)

# Still resolves to True

If statements can be chained together, nested, or used in any of the other usual ways standard for procedural languages.

if b or a:
   if a and b:
      if c:
         print(c)
      print(a, b)
   print(b, a)

elif can be used to prevent further if statements in a chain from executing if one is True.

x = True
y = False

if y:
   print(y)
elif x:
   print(x)
else:
   print(y, x)

And else can be used to define what will happen if none of the other statements trigger.

r = True
g = True
b = False

mystery = (r == True and (g == False or b == False) or r == False)

What is the value of mystery?