-
Notifications
You must be signed in to change notification settings - Fork 0
Programming Concepts 2: Conditionals
Conditionals are the way you branch you program execution. You can set certain blocks of code to execute in certain cases and set flags to trigger certain blocks to execute. The basic idea behind conditionals is Boolean Logic, which consist of only two values: True & False (sometimes referred to as 1 and 0). A conditional expression that evaluates to True is executed, and one evaluated to False is not. You can chain operations together using three operands: 'and', 'or', and 'not'. Operations can include checks for equality (==), inequality (!=), differences (>; <; >=; <=), presence in a data structure (is in; is not in), and Boolean value (True/False). Operators are evaluated in order from not to and to or.
Simple as the name implies, 'not' negates the value of the Boolean variable, flipping it from True to False and vice versa. You can use the not operator to negate a value, and the != in a conditional
>>> flag = True
>>> if flag: # Will execute, as flag is set to True
... print('flag is True')
...
flag is True
>>> flag = not flag # flag = False
>>> if not flag: # !flag = !False = True
... print('Got here!')
...
Got here!
>>>And requires both operands to be True for the expression to be true. Same as not, you can use the and operator to evaluate if multiple operands are all True. As many operands you pass, ALL must be true for an and operator to evaluate to True.
>>> flag1 = True
>>> flag2 = True
>>> if flag1 and flag2: # True and True -> True
... print('Made it!')
...
Made it!
>>> flag2 = False
>>> if flag1 and flag2: # True and False -> False
... print('Won't do anything...')
...
>>> or works much like and, but only requires one of the values to be True for the expression to be True.
>>> flag1 = True
>>> flag2 = False
>>> if flag1 or flag2: # True or False -> True
... print('Still got here!')
...
Still got here!
>>>Just like in your elementary math classes, equality operators work quite similarly in programming
>>> x = 5
>>> if x > 2:
... print('x is greater than 2')
...
x is greater than 2
>>> if x < 10:
... print('x is less than 10')
...
x is less than 10
>>> if x == 5:
... print('x equals 5')
...
x equals 5
>>> if x != 7:
... print('x does not equal 7')
...
x does not equal 7
>>>