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 mood = prompt("How are you feeling today?") // Define a variable and assign it a value

        if (mood === "happy") {
            console.log("You seem happy here's some ice cream");
            output.innerText += "You seem happy here's some ice cream";
        } else if (mood === "sad") {
            console.log("Cheer up! Things will get better");
            output.innerText += "Cheer up! Things will get better";
        } else {
            console.log("Im not sure what that mood is but hope you have a good day");
            output.innerText += "Im not sure what that mood is but hope you have a good day";
        }

    })();

</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 chose a smooth milk chocolate bar\n"; // Fill in message for milk chocolate
            } else if (chocolateType.toLowerCase() === "dark") { // Fill in dark
                output.innerText += "You chose a rich dark chocolate bar\n"; // Fill in message for dark chocolate
            } else {
                output.innerText += "That type of chocolate isn't available\n"; // Fill in message for unknown type
            }

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

        } else if (snackChoice == "3") { // Fill in the condition for candy
            let candyColor = prompt("You got candyChoose your color: red, green, or yellow");

            // Nested condition for candy color
            if (candyColor.toLowerCase() === "red") { // Fill in red
                output.innerText += "You got sweet red candy\n"; // Fill in message for red candy
            } else if (candyColor.toLowerCase() === "green") { // Fill in green
                output.innerText += "You got tangy green candy\n"; // Fill in message for green candy
            } else if (candyColor.toLowerCase() === "yellow") { // Fill in yellow
                output.innerText += "You got sour yellow candy\n"; // Fill in message for yellow candy
            } else {
                output.innerText += "That candy color isn't available\n"; // Fill in message for unknown candy color
            }

        } else {
            output.innerText += "Invalid choice! Please pick 1, 2, or 3.\n"; // Fill in message for invalid snack choice
        }

        // Challenge: 10% chance of extra cookie
        if (Math.random() < 0.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

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

<script>

    (() => {

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

        // 1) Temperature
        let temperature = 85;
        if (temperature > 80) {
            console.log("it’s hot outside");
            output.innerText += "it’s hot outside\n";
        } else {
            console.log("it’s nice outside");
            output.innerText += "it’s nice outside\n";
        }

        // 2 & 3) Score with prompt input
        function getScore() {
            let score = Number(prompt("enter your score"));
            if (score >= 90) {
                console.log("A");
                output.innerText += "A\n";
            } else if (score >= 80) {
                console.log("B");
                output.innerText += "B\n";
            } else if (score >= 70) {
                console.log("C");
                output.innerText += "C\n";
            } else {
                console.log("needs improvement");
                output.innerText += "needs improvement\n";
            }
        }
        getScore();

        // 4 & 5) Random number from 110, even or odd
        let number = Math.floor(Math.random() * 10) + 1;
        if (number % 2 === 0) {
            console.log(number + " is an even number");
            output.innerText += number + " is an even number\n";
        } else {
            console.log(number + " is an odd number");
            output.innerText += number + " is an odd number\n";
        }

        // 6 & 7) Day of the week with switch
        let day = prompt("enter a day of the week");
        switch (day.toLowerCase()) {
            case "monday":
                console.log("start of the week");
                output.innerText += "start of the week\n";
                break;
            case "tuesday":
                console.log("it’s tuesday");
                output.innerText += "it’s tuesday\n";
                break;
            case "wednesday":
                console.log("halfway through");
                output.innerText += "halfway through\n";
                break;
            case "thursday":
                console.log("almost friday");
                output.innerText += "almost friday\n";
                break;
            case "friday":
                console.log("last workday of the week");
                output.innerText += "last workday of the week\n";
                break;
            case "saturday":
            case "sunday":
                console.log("weekend");
                output.innerText += "weekend\n";
                break;
            default:
                console.log("weekday");
                output.innerText += "weekday\n";
        }

        // 8) Boolean loggedIn
        let loggedIn = true;
        if (loggedIn) {
            console.log("welcome back");
            output.innerText += "welcome back\n";
        } else {
            console.log("please log in");
            output.innerText += "please log in\n";
        }

        // 9) Weather
        let weather = "raining";
        if (weather === "raining") {
            console.log("it’s raining");
            output.innerText += "it’s raining\n";
        } else {
            console.log("go outside, it’s a nice day today");
            output.innerText += "go outside, it’s a nice day today\n";
        }

    })();

</script>
Results will appear here: