3.1 Homework and Popcorn Hacks
3.1 Homework and Popcorn Hacks
Popcorn Hack 1
memberOne = "Yuva"
memberTwo = "Kiruthic"
memberThree = "Pranav"
memberFour = "Anvay"
memberFive = "Rayhaan"
print(memberOne, memberTwo, memberThree, memberFour, memberFive)
Yuva Kiruthic Pranav Anvay Rayhaan
Popcorn Hack 2
fruits = {
"apple": "red",
"banana": "yellow",
"cherry": "red",
"date": "brown",
"fig": "purple",
"grape": "purple",
}
print("Apples are " + fruits["apple"])
print("Bananas are " + fruits["banana"])
print("Grapes are " + fruits["grape"])
Apples are red
Bananas are yellow
Grapes are purple
Popcorn Hack 3
%%js
let mixedArray = [true, "apple", false, "banana", true, "cherry"];
console.log(mixedArray); // the array contains both booleans and strings
<IPython.core.display.Javascript object>
Homework Hacks
Const and Let
%%js
const name = "Anvay"; // const because the name won't change
let age = 15; // let because the age might change
const city = "San Diego";
let hobby = "playing video games";
console.log("Name: " + name);
console.log("Age: " + age);
console.log("City: " + city);
console.log("Hobby: " + hobby);
/* How did I access the console?
1. I used the console.log() function to print the variables to the console.
2. I used my browser's developer tools (A.K.A "Inspect") to view the console output
3. I was able to view the log outputs in the "Console" tab of the developer tools
*/
function createSentence() {
let sentence = `${name} is ${age} years old, lives in ${city}, and enjoys ${hobby}.`;
console.log(sentence);
}
// Call the function to display the final sentence
createSentence();
<IPython.core.display.Javascript object>
Average Grade Calculator
%%js
// Function to calculate the average grade of a student
function calculateAverageGrade(grades) {
let total = 0;
for (let i = 0; i < grades.length; i++) { // loops through each grade in the array using index i
total += grades[i]; // Adds each grade to the total
}
// Calculate the average by dividing the total by the number of grades
let average = total / grades.length;
return average;
}
// Create an array of students with their info and grades
const students = [
{
name: "John",
age: 15,
grades: [90, 85, 88]
},
{
name: "Bob",
age: 16,
grades: [78, 82, 80]
},
{
name: "Mike",
age: 14,
grades: [95, 92, 90]
}
];
// Loop through each student in the array and calculate their average grade
for (let i = 0; i < students.length; i++) {
let student = students[i]; // Get each student's info
let averageGrade = calculateAverageGrade(student.grades); // Call the function to get average
student.averageGrade = averageGrade; // Add average grade to the student dictionary
// Log the info to console
console.log(`${student.name}, Age: ${student.age}, Average Grade: ${averageGrade.toFixed(2)}`);
}
<IPython.core.display.Javascript object>