Conditionals

Popcorn Hack 1 - Simple Conditionals

Instructions: Finish the code in the cell below (fill in underlines and add lines of code) so it becomes a functioning conditional. What you make is up to you!

Examples of conditionals you could use:

1) Define your mood today and give yourself ice cream if you’re happy

  • challenge 1: add “else if” conditionals that echo different strings based on different moods
  • challenge 2: add user input to define a “mood” variable

2) Define the weather today and echo “It’s sunny outside!” if it’s sunny

  • challenge 1: add “else if” conditionals that define other weather
  • challenge 2: let the user input today’s weather and respond automatically

3) Define your age as a variable and check whether you are an adult or a child.

  • challenge 1: expand to add other categories using “else if” conditionals
  • challenge 2: create a random age generator and test the conditional multiple times to see different results

The code is currently NOT functional. When you have completed this popcorn hack, the code should work. Have fun!

%%html

<div id="outputPH1">Results will appear here:<br></div>

<script>

(() => {

    const output = document.getElementById("outputPH1");

    let anishTailState = "wagging"; // Define a variable and assign it a value
    
    if (anishTailState === "normal") { // Anish is not wagging his tail :sob:
        console.log("Anish is not wagging his tail");
        output.innerText += "Anish is not wagging his tail :(";
    } else if (anishTailState === "ready") {
        console.log("Anish is about to wag his tail...");
        output.innerText += "Anish the neutral face is about to wag his tail...";
    } else if (anishTailState === "wagging") {
        console.log("Anish is wagging his tail!");
        output.innerText += "Anish is wagging his tail!";
    } else {
        console.log("ERROR: Invalid tail state!");
        // Don't output an error message to DOM, keep it nice and clean
    }

})();

</script>


Results will appear here:

Popcorn Hack 2 - Vending Machine

Instructions: This hack is a bit more complicated than the first. Points will be awarded based on effort and completion.

Analyze the block of code below. Then, complete the following instructions:

You’re hungry, so you go to your nearest vending machine for a snack. It makes you wonder if you’d be able to build your own. You can!… Digitally. Below, fill in the blanks so that when someone is prompted with food options, there are sub options within each food. (ex: Chocolate > Milk Chocolate)

1) Create variables:

  • snackChoice -> user input (prompt) to determine which random snack is chosen (number from 1-3)

2) Add basic conditionals determining what type of snack was chosen

3) Add nested if statements for extra behavior

  • Inside your chocolate condition:
    • Add user input to determine what type of chocolate the user wants
  • Inside your candy condition:
    • Add user input to determine what color candy the user wants

4) Challenge (OPTIONAL):

  • Make it so that there is a 10% chance of the vending machine giving you an extra cookie!
%%html

<div id="outputPH2">Results will appear here:<br></div>

<script>

(() => {

const output = document.getElementById("outputPH2");

let snackChoice = prompt("Choose a number: 1, 2, or 3 to get a snack!");

    if (snackChoice === "1") { // Fill in the condition for chocolate bar
        let chocolateType = prompt("You got a chocolate bar! Choose your type: milk or dark?");
        
        // Nested condition for chocolate type
        if (chocolateType.toLowerCase() === "milk") { // Fill in milk
            output.innerText += "You get a cup of milk chocolate!\n"; // Fill in message for milk chocolate
        } else if (chocolateType.toLowerCase() === "dark") { // Fill in dark
            output.innerText += "Heres a cup of dark chocolate!\n"; // Fill in message for dark chocolate
        } else if (chocolateType.toLowerCase() === "coffie") {
            output.innerText += "No Adya we don't have coffie go ask someone else\n";
        } else {
            output.innerText += "We don't have that type of chocolate...\n"; // Fill in message for unknown type
        }

    } else if (snackChoice == "2") { // Fill in the condition for chips
        output.innerText += "You get a free bag of chips!\n"; // Fill in message for chips

    } else if (snackChoice == "3") { // Fill in the condition for candy
        let candyColor = prompt("You got candy! Choose your color: red, green, or yellow?");
        
        // Nested condition for candy color
        if (candyColor.toLowerCase() === "red") { // Fill in red
            output.innerText += "Heres your red candy!\n"; // Fill in message for red candy
        } else if (candyColor.toLowerCase() === "green") { // Fill in green
            output.innerText += "Heres your green candy\n"; // Fill in message for green candy
        } else if (candyColor.toLowerCase() === "yellow") { // Fill in yellow
            output.innerText += "You get yellow candy! I don't know why you picked this...\n"; // Fill in message for yellow candy
        } else {
            output.innerText += "Okay please pick A COLOR LISTED since you didn't you now don't get candy :(\n"; // Fill in message for unknown candy color
        }

    } else {
        output.innerText += "No candy for you because you picked an invalid option\n"; // Fill in message for invalid snack choice
    }

    // Challenge: 10% chance of extra cookie
    if (Math.floor(Math.random() * 10) == 1) { // How would you create a random number with a 10% chance of fitting some criteria?
        output.innerText += "Bonus treat! The machine gives you an extra cookie!\n";
    }

})();

</script>
Results will appear here:

Homework

Complete the following questions in the next code block.

1) Create a variable called “temperature” that defines a temperature. If it’s above 80 degrees, print “It’s hot outside!”. Otherwise, print “It’s nice outside.”

2) Create a variable called “score”. If score >= 90 print “A”, 80-89 print “B”, 70-79 print “C”, otherwise print “Needs improvement.”

3) Add a function to your “score” variable that prompts the user to input their score.

4) Define a variable “number”. If it’s even, print “Even Number”; otherwise, print “Odd number.”

5) Instead of defining the variable “number,” make the number a random integer from 1-10.

6) Define a variable called “day” (like ‘Monday’, ‘Tuesday’, etc.) and use a switch statement to print a message for that day.

7) Add statements to the previous conditional: If today is ‘Saturday’ or ‘Sunday’, print “Weekend!”; else print “Weekday!”.

8) Create a boolean called “loggedIn” (true or false). If true, print “Welcome back!”, otherwise print “Please log in.”

9) Define a variable “weather”. If it’s raining, print “It’s raining.” Else, print “Go outside, it’s a nice day today!”

10) Extra Credit: Submit the original OOP Breakout Game Code (found on OpenCS) after making the following edits:

  • Add a conditional to the game that changes the color of the ball every time it hits the wall or another brick.
  • Try making the ball do something different when it collides (ex: speed up, shrink, glow).
  • Make sure your code is functional before you submit!
  • Have fun!
%%html

<input type="number" id="scoreInput" placeholder="Enter score here...">
<button type="button" id="scoreButton" onclick="promptScore()">Get Score</button>
<div id="outputHW">Results will appear here:<br></div>

<script>

(() => {

    const output = document.getElementById("outputHW");

    console.log("Code, code, code!");
    output.innerText += "Code, code, code!\n";

    // YOUR CODE HERE
    function display(text) {
        console.log(text);
        output.innerText += text + "\n";
    }

    // 1
    let temprature = -80;
    if (temprature > 80) {
        display("It's hot outside!");
    } else {
        display("It's nice outside!");  // Do you see the flaw with your logic now?
    }

    // 2
    let score = 103;
    if (score >= 90) {
        display("A");
    } else if (score >= 80) {
        display ("B");
    } else if (score >= 70) {
        display("C");
    } else {
        display("Needs improvement");
    }

    // 3
    let scoreInput = document.getElementById("scoreInput");
    window.promptScore = function() {
        const score = Number(scoreInput.value);
        display(`Score updated to: ${score}`);
    }

    // 4
    let number = 3;
    if (number % 2 === 0) {
        display("Number is even!");
    } else {
        display("Number is odd!");
    }

    // 5
    let randNum = Math.floor(Math.random() * 10) + 1;
    if (randNum % 2 === 0) {
        display("Random number is even!");
    } else {
        display("Random number is odd!");
    }
    
    // 6 & 7
    let day = "Tuesday";
    switch (day) {
        case "Sunday":
            display("Enjoy your weekend for another day!");
            display("Weekend!");
            break;
        case "Monday":
            display("Time to go back to work or school :(");
            display("Weekday!");
            break;
        case "Tuesday":
            display("MONDAY IS OVERRRRRRR!!!!");
            display("Weekday!");
            break;
        case "Wednesday":
            display("Short day time!");
            display("Weekday!");
            break;
        case "Thursday":
            display("The weekend is almost there, only a couple more days!");
            display("Weekday!");
            break;
        case "Friday":
            display("ITS FRIDAY YES YES");
            display("Weekday!");
            break;
        case "Saturday":
            display("The weekend has arrived!");
            display("Weekend!");
            break;
        default:
            display("Invalid day!");
    }

    // 8
    let loggedIn = false;
    if (loggedIn) {
        display("Welcome back!");
    } else {
        display("Please log in");
    }

    // 9
    let weather = "rainy";
    if (weather === "rainy") {
        display("Its raining");
    } else {
        display("Go outside! Its a nice day today!");
    }

    // 10 -- EXTRA CREDIT
})();

</script>

Results will appear here: