Skip to the content.

Lessons 3.5 Hacks

3.5

Popcorn Hacks

3.5.3

Hack 1

Check Number: Evaluates if number is less than 0. Output: Logs whether the number is negative or non-negative.

def number_checker():
    try:
        number = float(input("Please enter a number:"))
        if number < 0:
            print("This number is negative.")
        if number == 0:
            print("This number is neither positive nor negative.")
        else:
            print("This number is non-negative.")
    except ValueError:
        print("Please try again and enter a valid number")

number_checker()
This number is non-negative.

Hack #3

Check Vowel: Checks if char is in the string ‘aeiou’. Output: Prints whether the character is a vowel or not.

chara = input("Please enter a character:")

def vowel_checker(chara):
    vowels = "aeiou"
    if chara.lower() in vowels:
        print("The character",chara,"is a vowel")
    else:
        print("The character",chara,"is not a vowel")
        
if len(chara) == 1:
    vowel_checker(chara)
else:
    print("Please enter a single character and try again.")
The character a is a vowel

3.5.4 Javascript Booleans

Hack 1

Use logical operators to identify if the inputted number is even or odd.

%%html
<script>
number1 = 2
number2 = 7

function check_odd_even(number){
    if (number % 2 == 0){
        return "even"
    } else{
        return "odd"
    }
}

console.log(`${number1} is ${check_odd_even(number1)}`)
console.log(`${number2} is ${check_odd_even(number2)}`)
</script>

Alternate hack: Use logical operators to identify if the user-inputted number is even or odd.

%%html
<script>
input = prompt("Enter a number to check if it is even/odd:")
let number3 = parseInt(input)

function check_odd_even(number){
    if (number % 2 == 0){
        return "even"
    } else{
        return "odd"
    }
}

console.log(`${number3} is ${check_odd_even(number3)}`)
</script>

Hacks

3.5.3 Python Boolean Hacks

Hack 1

Create a Truth Table: Develop a truth table for a given logical expression.

import itertools

# create table!
headers = ['M', 'A', 'M AND A', 'NOT (M AND A)', 'NOT M OR NOT A', 'M OR A', 'NOT (M OR A)', 'NOT M AND NOT A']

# generate all possible t/f combinations
# [(True, True), (True, False), (False, True), (False, False)]
values = list(itertools.product([True, False], repeat=2))


def print_truth_table():
    # using f-strings, make headers of table and seperate with dashes
    print(f"{' | '.join(headers)}")
    print("-" * 80)
    
    # truth table statements
    for M, A in values:
        m_and_a = M and A
        not_m_and_a = not (M and A)
        not_m_or_not_a = not M or not A
        m_or_a = M or A
        not_m_or_a = not (M or A)
        not_m_and_not_a = not M and not A
        
       # format the table
        print(f"{M:<5} | {A:<5} | {m_and_a:<9} | {not_m_and_a:<12} | {not_m_or_not_a:<13} | {m_or_a:<7} | {not_m_or_a:<12} | {not_m_and_not_a:<13}")


print_truth_table()
M | A | M AND A | NOT (M AND A) | NOT M OR NOT A | M OR A | NOT (M OR A) | NOT M AND NOT A
--------------------------------------------------------------------------------
1     | 1     | 1         | 0            | 0             | 1       | 0            | 0            
1     | 0     | 0         | 1            | 1             | 1       | 0            | 0            
0     | 1     | 0         | 1            | 1             | 1       | 0            | 0            
0     | 0     | 0         | 1            | 1             | 0       | 1            | 1            

Hack 2

Design a Game Using De Morgan’s Law: Create a game that uses De Morgan’s Law to simplify yes or no functions.

import random
import ipywidgets as widgets
from IPython.display import display, clear_output

def ran_truth_val():
    return random.choice([True, False])

def check_answer(correct_answer, player_answer):
    return correct_answer == player_answer

def play_level(expression, correct_answer):
    print(expression)
    player_answer = input("Your answer (True/False): ").strip()
    
    if player_answer not in ["True", "False"]:
        print("Invalid input! Please enter True or False.")
        return False
    
    player_answer = player_answer == "True"
    
    if check_answer(correct_answer, player_answer):
        print("Correct!\n")
        return True
    else:
        print("Incorrect! The correct answer was {correct_answer}. Game Over.\n")
        return False

def main():
    clear_output()
    print("Welcome to the De Morgan's Law Game!")
    
    # Level 1
    I = ran_truth_val()
    O = ran_truth_val()
    expression = "Level 1: Solve this expression using De Morgan's Law: not (I or O)\nI = {I}, O = {O}"
    correct_answer = (not I) and (not O)
    
    if not play_level(expression, correct_answer):
        return
    
    # Level 2
    J = ran_truth_val()
    K = ran_truth_val()
    expression = "Level 2: Solve this expression using De Morgan's Law: not (J and K)\nJ = {J}, K = {K}"
    correct_answer = (not J) or (not K)
    
    if not play_level(expression, correct_answer):
        return
    
    print("Congratulations! You passed all levels.")


play_button = widgets.Button(description="Play")


def on_play_button_clicked(b):
    main()


play_button.on_click(on_play_button_clicked)


display(play_button)
Button(description='Play', style=ButtonStyle())

3.5.4 JavaScript Boolean Hacks

To see the below two hacks in action, visit here.

Hack 1

Password Creator Hack: Check whether a user’s password meets certain criteria

  1. The password must be at least 10 characters long.
  2. It must include both uppercase and lowercase letters.
  3. It must contain at least one number.
  4. It must not contain any spaces.
%%html

<script>
    console.log("Password requirements:\n1. The password must be at least 10 characters long.\n2. It must include both uppercase and lowercase letters.\n3. It must contain at least one number.\n4. It must not contain any spaces.")

    user_password=prompt("Please create a password:")

    function passwordChecker(user_password) {
        // character checking
        const hasUppercase = /[A-Z]/;
        const hasLowercase = /[a-z]/;
        const hasNumber = /[0-9]/;
        const hasSpace = /\s/;

        // test for each
        const lengthValid = user_password.length >= 10;
        const hasUpper = hasUppercase.test(user_password);
        const hasLower = hasLowercase.test(user_password);
        const hasNum = hasNumber.test(user_password);
        const noSpace = !hasSpace.test(user_password);  
        
        // if it doesnt have every requirement...
        if (!(lengthValid && hasUpper && hasLower && hasSpace)){
            console.log("This password is not valid. Please create a valid password:")
            return false;
        }

        return true;
}
</script>

Hack 2

Personality Quiz Hack: Create a simple multiple-choice personality quiz that gives you a brief description of your personality based on the questions answered from the quiz

  1. Must have at least 10 different questions
  2. Must be multiple choice
  3. Must have multiple different outputs based on results
%%html

<h1>Seasons Quiz</h1>
<h3>Take this quiz to find out what season you are!</h3>
Disclaimer: I made this quiz at 1AM

  <form id="quiz-form">
    <div class="question">
        <p>1. What's your favorite way to spend your free time?</p>
        <input type="radio" name="q1" value="winter"> A. Spending a night in<br>
        <input type="radio" name="q1" value="spring"> B. Trying something new<br>
        <input type="radio" name="q1" value="summer"> C. Doing something you've been thinking about starting on a whim<br>
        <input type="radio" name="q1" value="fall"> D. Journaling, or having deep conversations with your friends<br>
    </div>

    <div class="question">
        <p>2. What kind of movies do you enjoy?</p>
        <input type="radio" name="q2" value="summer"> A. Action and adventure<br>
        <input type="radio" name="q2" value="winter"> B. Nostalgic favorites<br>
        <input type="radio" name="q2" value="spring"> C. Anything new that's come out!<br>
        <input type="radio" name="q2" value="fall"> D. Dramas<br>
      </div>
      
    <div class="question">
        <p>3. What's your favorite color?</p>
        <input type="radio" name="q3" value="fall"> A. Oranges and browns<br>
        <input type="radio" name="q3" value="spring"> B. Anything bright!<br>
        <input type="radio" name="q3" value="summer"> C. Warmer colors<br>
        <input type="radio" name="q3" value="winter"> D. Cooler colors<br>
    </div>
  
    <div class="question">
        <p>4. What would your friends say about you?</p>
        <input type="radio" name="q4" value="fall"> A. Quiet and observant<br>
        <input type="radio" name="q4" value="winter"> B. Relaxed and laid back<br>
        <input type="radio" name="q4" value="summer"> C. Brave and spontaneous<br>
        <input type="radio" name="q4" value="spring"> D. Vibrant and fun<br>
    </div>
      
    <div class="question">
        <p>5. Which quote stands out to you?</p>
        <input type="radio" name="q5" value="spring"> A. In the springtime, the heart regrows hope<br>
        <input type="radio" name="q5" value="winter"> B. What good is the warmth of summer, without the cold of winter to give it sweetness?<br>
        <input type="radio" name="q5" value="fall"> C. Autumn shows us how beautiful it is to let things go<br>
        <input type="radio" name="q5" value="summer"> D. Summertime is always the best of what might be<br>
    </div>

    <div class="question">
        <p>6. How do you prefer to plan your day?</p>
        <input type="radio" name="q6" value="spring"> A. In my planner<br>
        <input type="radio" name="q6" value="winter"> B. Why plan? Just hang around and relax.<br>
        <input type="radio" name="q6" value="fall"> C. In a way that only includes activities most important to me<br>
        <input type="radio" name="q6" value="summer"> D. With a full, packed itinerary of all the new things to do<br>
    </div>

    <div class="question">
      <p>7. Would you consider yourself a type A person or type B? (A = planner, detail-oriented, B = let it happen)</p>
      <input type="radio" name="q7" value="spring"> A. A for sure!<br>
      <input type="radio" name="q7" value="summer"> B. Hahahahah yeah I\'m type B <br>
      <input type="radio" name="q7" value="fall"> C. Does it matter?<br>
      <input type="radio" name="q7" value="winter"> D. What<br>
    </div>

    <div class="question">
      <p>8. What is your favorite class?</p>
      <input type="radio" name="q8" value="summer"> A. Ceramics! It\'s so different from anything I've ever taken before<br>
      <input type="radio" name="q8" value="winter"> B. Anything history<br>
      <input type="radio" name="q8" value="spring"> C. Anything STEM<br>
      <input type="radio" name="q8" value="fall"> D. Pyschology <br>
    </div>
    
    <div class="question">
      <p>9. Why would you make me add 10 questions to this quiz?</p>
      <input type="radio" name="q9" value="fall"> A. Such is life<br>
      <input type="radio" name="q9" value="spring"> B. Not sure!<br>
      <input type="radio" name="q9" value="summer"> C. I don\'t mind it<br>
      <input type="radio" name="q9" value="winter"> D. Who cares<br>
    </div>

    <div class="question">
      <p>10. What's your favorite season?</p>
      <input type="radio" name="q10" value="fall"> A. Fall<br>
      <input type="radio" name="q10" value="winter"> B. Winter<br>
      <input type="radio" name="q10" value="summer"> C. Summer<br>
      <input type="radio" name="q10" value="spring"> D. Spring<br>
    </div>

    <button type="button" onclick="finalResult()">Submit</button>
</form>

<h2>Your Season: <span id="result"></span></h2>

<script>
  function finalResult() {
    let score = {
      winter: 0,
      spring: 0,
      summer: 0,
      fall: 0
    };

    // Grab form data
    const form = document.getElementById('quiz-form');
    const formData = new FormData(form);

    // Tally scores
    for (let [key, value] of formData.entries()) {
      score[value]++; // Fix variable name to match the score object
    }

    // Determine result
    let result = '';
    const maxScore = Math.max(score.winter, score.spring, score.summer, score.fall);

    // Share answer
    if (maxScore === score.winter) {
      result = "Winter: You love taking time to relax and reflect";
    } else if (maxScore === score.spring) {
      result = "Spring: You love new beginnings and fresh starts";
    } else if (maxScore === score.summer) {
      result = "Summer: You are adventurous and enjoy trying new things";
    } else if (maxScore === score.fall) {
      result = "Fall: You are reflective and introspective yet curious";
    }

    // Display the result
    document.getElementById('result').textContent = result;
  }
</script>