3.5 Boolean Expresssions

Boolean expressions have two states, "True" and "False" (basically "1" and "0").

Rational Operators

Operators ==, !=, >, <, >=, and <= are used to compare values. They can return true of false depending on the statement. They work with both integers and strings.

print("True:", 4 == 4)
print("True:",1 > 0)
print("False:",7 < 3)
print("True:", 5 < 6)
print("False:",7 > 8)
print("True:",3 == 3)
print('')

# Same as above, but now for other values other than int
print('True:',"as" == "as")
print("False",True == False)
print("False:",[2,3,1] != [2,3,1])
print("True:",'af' < 'bc')
print("False:",'ce' > 'cf')
print("True:",[1,'b'] > [1,'a'])
True: True
True: True
False: False
True: True
False: False
True: True

True: True
False False
False: False
True: True
False: False
True: True

Logical Operators

Operators like "and", "or", or "not" can be used to assess the state of boolean operands. See their use below.

print("True:", True or False)
print("False:", not True)
print("True:", True and True)
print("False:", not True)
print("False:", True and False)
print("True:", not False)
True: True
False: False
True: True
False: False
False: False
True: True

3.6 Conditionals

Conditionals only make certain things happen when conditions are met. This is most often seen with if/else statements.

Vocabulary

Copied from their blog.

Algorithm - A set of instructions that accomplish a task.

Selection - The process that determines which parts of an algoritm is being executed based on a condition that is true or false.

If/Else Statements

if and else statements are the primary conditional statements. See their basic use below.

number = 3          # value that will affect true or false statement
if number == 5:     # if part determines if the statement is true or false compared to another part of the program
    print("Yes,", str(number), "does equal 5.")
else:               #else part only executes if the if part is false
    print("No, " + str(number) + " does not equal 5.")
No, 3 does not equal 5.

As their blog says, solo if statements can be used as sort of interruptions when certain conditions are met. Here is there example.

progress = 0
while progress < 100:
    print(str(progress) + "%")
    
    if progress == 50:
        print("Half way there")

    progress = progress + 10
print("100%" + " Complete")
0%
10%
20%
30%
40%
50%
Half way there
60%
70%
80%
90%
100% Complete

3.7 Nested Conditional Statements

Basically conditionals inside of conditional statements that make things happen on top of the other stuff. Vague, but it makes sense.

Examples

Here is the example provided by the group to show nested conditionals.

age = 19
isGraduated = False
hasLicense = True

# Look if person is 18 years or older
if age >= 18:
    print("You're 18 or older. Welcome to adulthood!")

    if isGraduated:
        print('Congratulations with your graduation!')
    if hasLicense:
        print('Happy driving!')
You're 18 or older. Welcome to adulthood!
Happy driving!

Here's my take on the nested conditionals example.

year = 2022
if (year == 1776): 
    print("The U.S. just declared independence, didn't they?")
else: 
    print("The U.S. has already gained independence, or perhaps doesn't exist...") 
if (year == 1848): 
    print("Gold was just struck in California, wasn't it?")
else: 
    print("The Gold Rush is an afterthought, or perhaps hasn't yet happened...")
if (year == 2022):
    print("Elon Musk bought Twitter not too long ago, didn't he?")
else:
    print("Perhaps Elon Musk and Twitter do not yet exist, or are old news...")
if (year == 3000):
    print("Flying cars have just been invented, haven't they?")
else: 
    print("You'll have to wait a bit longer for flying cars...")
The U.S. has already gained independence, or perhaps doesn't exist...
The Gold Rush is an afterthought, or perhaps hasn't yet happened...
Elon Musk bought Twitter not too long ago, didn't he?
You'll have to wait a bit longer for flying cars...

Homework

Here is my take on the binary homework.

Hacks

System to repeat the user input if it is not within the valid range of 8-bit binary.

More conditionals with try and except

A Frontend version on top of the Python version.

def DecimalToBinary(input):
    if 0 <= input <= 255:
        pass
    else:
        print(int(input) + "Intentional Error to Restart Loop")
    i = 7
    binary = ""
    while i >= 0:
        if input % (2**i) == input:
            binary += "0"
            i -= 1
        else:
            binary += "1"
            input -= 2**i
            i -= 1
    return binary
 
# function to reverse the string
def reverse(strs):
    print(strs[::-1])
 
# Driver Code
num = 67
print("The reverse of 67 in binary is:", end=" ")
reverse(DecimalToBinary(num))

# input box
def getUserInput():
    try:
        userinp = int(input("Input an integer between 0 and 255."))
        userbin = DecimalToBinary(userinp)
        print('"' + str(userinp) + '" in binary is "' + userbin + '".')
    except:
        print("Invalid input.")
        getUserInput()

getUserInput()
The reverse of 67 in binary is: 11000010
Invalid input.
Invalid input.
"34" in binary is "00100010".

Here's the frontend version:

Convert to binary...

And here's the code behind it:

<p style="font-family:">Convert <input id="bininput" style="text-align:left" type="number" min="0" minlength="1" maxlength="3" max="255" value="0"> to binary...</p>
<button id="convertbtn">CONVERT</button>
<p id="output"></p>

<script>
    console.log('initialized accurately')
    var opbox = document.getElementById("output");
    var convertbtn = document.getElementById("convertbtn");
    var inpbox = document.getElementById("bininput");
    function DecimalToBinary(parameter) {
        var input = Number(parameter);
        if (input < 0) {
            console.log('invalidreturn');
            return "Invalid input.";
        } else if (input > 255) {
            console.log('invalidreturn');
            return "Invalid input.";
        };
        var i = 7;
        var binary = "";
        while (i >= 0) {
            if (input % (2**i) == input) {
                binary += "0";
                i -= 1;
            } else {
                binary += "1";
                input -= 2**i;
                i -= 1;
            };
        };
        return binary;
    }
    convertbtn.onclick = function() {
        console.log('pressed');
        var binconvert = DecimalToBinary(Number(inpbox.value));
        if (binconvert == "Invalid input.") {
            console.log('invalidinput')
            opbox.innerHTML = "Invalid input.";
        } else {
            console.log('valid')
            opbox.innerHTML = String(Number(inpbox.value)) + " in binary is " + String(binconvert) + ".";
        };
    };
</script>