Boolean Expressions, Conditionals and Nested Conditionals Lesson Notes
Based on the notebooks template by Ryan, Lucas, Haoxuan and Shivansh.
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'])
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)
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.")
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")
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!')
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...")
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()
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>