Section 5 - Boolean Expressions

Intro

Booleans:

  • Two values True (1) and False (0)

Vocab

  • Boolean
  • Relational Operator
  • Logical Operator

Boolean Operators

Relational Operators

  • Works between any two values that are hte same type
  • Consist of operators: ==, !=, >, <, >=, <=
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",TrueFalse)
print("False:",[2,3,1][2,3,1])
print("True:",'af''bc')
print("False:",'ce''cf')
print("True:",[1,'b'][1,'a'] 
print('')
  Input In [6]
    print("True:",4 4)
                    ^
SyntaxError: invalid syntax

Logical Operators

  • Operators that work on oeprand(s) to produce a single b9oolean result
print("True:", True False)
print("False:",  True)
print("True:", True True)
print("False:",  True)
print("False:", True False)
print("True:",  False)
  Input In [5]
    print("True:", True False)
                        ^
SyntaxError: invalid syntax

Combination of Relational and Logical Operators and the Procedure of Operations

  • Relational Operators first, then Logical operators
print( 3 3 4 6 5 7)
  Input In [4]
    print( 3 3 4 6 5 7)
             ^
SyntaxError: invalid syntax

Section 6 - Conditionals

Vocab

  • 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.

What is a conditional?

  • Statement that affects flow/outcome of a program
  • Executing different statements based on the result of ture or false statement, or boolean expression
  • Used in many programming lanuages

If/Else Statements

Example:

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, 5 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

Just if statment, interruption rather than yes or no responsse

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

Section 7 - Nested Conditionals

Nexted Conditional Statements

  • consist of conditional statements within conditional statements

Fomrated of nested conditional in Psuedocode

IF (condition 1)
{
    <first block of statements>
}
ELSE
{
    IF (condition 2)
    {
        <second block of statements>
    }
    ELSE
    {
        <third block of statements>
    }
}

Nested condtional examples:

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!')
print("What is your grade on the quiz")
grade = int(input('What is your grade on the quiz'))
if grade >= 90:
    print("Awesome grade. You do not need to make up the quiz.")
else:
    if grade >= 70:
        print("You may retake the quiz next class for up to an A.")
    else:
        print("We will review next class together and retake later.")

Examples + Try it!

age = int(input("How old are you?:")); 
if (age < 0): 
    print("You do not exist."); 
else: 
    print("You are alive."); 
if (age<16): 
    print("You can't drive yet."); 
else: 
    print("You can drive."); 
if (age < 18): 
    print("You aren't an adult yet"); 
else:
    print("You are an adult."); 
if (age < 21): 
    print("You can't drink yet."); 
else: 
    print("You can drink.");
You are alive.
You can drive.
You aren't an adult yet
You can't drink yet.
if conditionA:
    # Code here executes when 'conditionA' is True
else:
    # Code that runs when 'conditionA' is False

    if conditionB:
        # Code that runs when 'conditionA' is False
        # and 'conditionB' is True
n=int(input('Enter marks: '))

# checking the conditions
if  n>=75:
    if n >=95:
        print('Excellent')
    else:
        print('Pass')
else:
    print('Fail')
if (condition 1)
    if (condition 2)
        #first block of statement
    else 
        #second block of statement
else
    if (condition 3)
        #third block of statement
    else 
        #fourth block of statement

Challenge #1: Create your own Nested Conditional, with a if/else statement inside the else code of an if/else statement.

x = int(input("What is your age?:"))
y = 16
z = 18

def function(x, y, z):
    if(x >= y):
        if(x < z):
            print("16-17: You can drive, but you aren't an adult yet.")
        else:
            print("18 and up: You're an adult.")
    else:
        if(x >= 13):
            print("13-15: You're a teenager, but you can't drive yet.")
        else:
            print("12 and below: You're not a teenager yet.")

function(x, y, z)
16-17: You can drive, but you aren't an adult yet.

Challenge #2: Create your own Nested Conditional with operators and comparing values

burger = 5
fries = 3
money = int(input("How much money do you have?:"))

if money >= fries:
    if money < burger:
        print("You only have enough money to purchase fries.")
    elif money < (burger+fries):
        print("You have enough money to purchase fries OR a burger.")
    elif money >= (burger+fries):
        print("You have enough money to purchase both fries AND a burger.")
else:
    print("Sorry, you don't have enough money to purchase anything")
You have enough money to purchase both fries AND a burger.

Homework/Hacks

our homework we have decided for a decimal number to binary converter. You must use conditional statements within your code and have a input box for where the decimal number will go. This will give you a 2.7 out of 3 and you may add anything else to the code to get above a 2.7.

Below is an example of decimal number to binary converter which you can use as a starting template.

I didn't use the provided template and started from scratch. I met the requirements for a 2.7 (conditional statements within the code and input for decimal number).

Extra for 2.7+: Check if input is a decimal number or not, if not then no conversion, and decimal to octal converter.

x = input("Enter a decimal number:")

## Decimal to Binary
numsBin = []
def convertBin(x):
    if x.isnumeric():
        x = int(x)
        while x/2 != 0:
            rem = x % 2
            numsBin.append(rem)
            x = int(x/2)
        numsBin.reverse()
        binary = " "
        for i in numsBin:
            binary = binary + str(i)
        return binary
    else:
        print("Not a decimal number.")
        quit

print(str(x) + " to binary: " + convertBin(x))


## Decimal to Octal
numsOct = []
def convertOct(x):
    if x.isnumeric():
        x = int(x)
        if x < 8:
            octal = x
            return octal
        else:
            while x/8 != 0:
                rem = x % 8
                numsOct.append(rem)
                x = int(x/8)
            numsOct.reverse()
            octal = " "
            for i in numsOct:
                octal = octal + str(i)
            return octal
    else:
        print("Not a decimal number.")
        quit

print(str(x) + " to octal: " + str(convertOct(x)))
1392 to binary:  10101110000
1392 to octal:  2560