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");

    // --- Mood ---
    let mood = prompt("How are you feeling today? (happy, sad, tired)");
    
    if (mood && mood.toLowerCase() === "happy") {
        console.log("You’re happy today! Have a nice treat.");
        output.innerText += "You’re happy today! Have a nice treat.\n";
    } else if (mood && mood.toLowerCase() === "sad") {
        console.log("Feeling sad? Take a break and relax.");
        output.innerText += "Feeling sad? Take a break and relax.\n";
    } else {
        console.log("You might be tired — get some rest.");
        output.innerText += "You might be tired — get some rest.\n";
    }

    // --- Weather ---
    let weather = prompt("What's the weather like today? (sunny, rainy, cloudy, snowy, windy)");
    
    if (weather && weather.toLowerCase() === "sunny") {
        console.log("It's sunny outside.");
        output.innerText += "It's sunny outside.\n";
    } else if (weather && weather.toLowerCase() === "rainy") {
        console.log("It's raining — bring an umbrella.");
        output.innerText += "It's raining — bring an umbrella.\n";
    } else if (weather && weather.toLowerCase() === "cloudy") {
        console.log("It's cloudy today.");
        output.innerText += "It's cloudy today.\n";
    } else if (weather && weather.toLowerCase() === "snowy") {
        console.log("It's snowy — dress warmly.");
        output.innerText += "It's snowy — dress warmly.\n";
    } else {
        console.log("It's windy today.");
        output.innerText += "It's windy today.\n";
    }

    // --- Age ---
    let ageInput = prompt("Enter your age:");
    let age = parseInt(ageInput, 10);

    if (age <= 12) {
        console.log("You are a Child.");
        output.innerText += "You are a Child.\n";
    } else if (age <= 17) {
        console.log("You are a Teen.");
        output.innerText += "You are a Teen.\n";
    } else if (age <= 64) {
        console.log("You are an Adult.");
        output.innerText += "You are an Adult.\n";
    } else {
        console.log("You are a Senior.");
        output.innerText += "You are a Senior.\n";
    }

})();
</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! (10% chance of a free cookie!)");

    if (snackChoice == "1") {
        let chocolateType = prompt("You got a chocolate bar! Choose your type: milk or dark?");
        if (chocolateType.toLowerCase() === "milk") {
            output.innerText += "\nYou got milk chocolate!";
        } else if (chocolateType.toLowerCase() === "dark") {
            output.innerText += "\nYou got dark chocolate!";
        } else {
            output.innerText += "\nYou didn't choose milk or dark, no chocolate for you!";
        }
    } else if (snackChoice == "2") {
        output.innerText += "\nYou got chips!";
    } else if (snackChoice == "3") {
        let candyColor = prompt("You got candy! Choose your color: red, green, or yellow?");
        if (candyColor.toLowerCase() === "red") {
            output.innerText += "\nYou ate a red candy!";
        } else if (candyColor.toLowerCase() === "green") {
            output.innerText += "\nYou ate a green candy!";
        } else if (candyColor.toLowerCase() === "yellow") {
            output.innerText += "\nYou ate a yellow candy!";
        } else {
            output.innerText += "\nYou didn't pick a valid candy color!";
        }
    } else {
        output.innerText += "\nInvalid snack choice!";
    }

    if (Math.random() <= 0.1) {
        output.innerText += "\nBonus treat! The machine gives you an extra cookie!";
    }
})();
</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

<h2>Homework</h2>
<input type="number" id="hwScoreInput" placeholder="Enter your test score">
<button id="submitHW">Show results</button>
<div id="outputHW">Results will appear here:<br></div>

<script>
(() => {
    const outputHW = document.getElementById("outputHW");
    const submitHW = document.getElementById("submitHW");

    function writeHW(msg){
        outputHW.innerText += "\n" + msg;
    }

    submitHW.addEventListener("click", () => {
        outputHW.innerText = "";

        let temp = Math.floor(Math.random()*100);
        writeHW(`Temperature: ${temp}`);
        if (temp > 80) writeHW("It's hot outside!");
        else writeHW("It's nice outside.");

        let score = parseInt(document.getElementById("hwScoreInput").value);
        writeHW(`Score: ${score}`);
        if (score >= 90) writeHW("Grade: A");
        else if (score >= 80) writeHW("Grade: B");
        else if (score >= 70) writeHW("Grade: C");
        else writeHW("Needs improvement");

        let number = Math.floor(Math.random()*10) + 1;
        writeHW(`Random number: ${number}`);
        writeHW(number % 2 === 0 ? "Even Number" : "Odd Number");

        const days = ["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"];
        let randomDay = days[Math.floor(Math.random()*7)];
        let isWeekend = (randomDay === "Saturday" || randomDay === "Sunday");
        writeHW(`Day: ${randomDay} - ${isWeekend ? "Weekend" : "Weekday"}`);

        let loggedIn = Math.random() >= 0.5;
        writeHW(`Logged in: ${loggedIn}`);
        writeHW(loggedIn ? "Welcome back!" : "Please log in");

        const weatherArr = ["rainy","sunny"];
        let weather = weatherArr[Math.floor(Math.random()*2)];
        writeHW(`Weather: ${weather}`);
        writeHW(weather === "rainy" ? "It's raining." : "Go outside, it's nice today!");
    });
})();
</script>

Homework

Results will appear here: