### Lesson 3.5.1 -4 Popcorn hacks and Homework hacks
Python popcorn hack 1
Popcorn Hack #1
Check Number: Evaluates if number is less than 0. Output: Logs whether the number is negative or non-negative.
def check_number():
try:
number = float(input("Enter a number: "))
if number < 0:
print("The number is negative.")
else:
print("The number is non-negative.")
except ValueError:
print("Invalid input! Please enter a valid number.")
check_number()
The number is non-negative.
Python Popcorn hack 3
Check Vowel: Checks if char is in the string ‘aeiou’. Output: Prints whether the character is a vowel or not.
def check_vowel(char):
vowels = 'aeiou'
if char.lower() in vowels:
print(f"The character '{char}' is a vowel.")
else:
print(f"The character '{char}' is not a vowel.")
char = input("Enter a character: ")
if len(char) == 1:
check_vowel(char)
else:
print("Please enter a single character.")
The character 'e' is a vowel.
Python Homework Hack 1
Create a Truth Table: Develop a truth table for a given logical expression.
def truth_table():
print(f"{'A':<5} {'B':<5} {'A or B':<10} {'A and (A or B)':<20}")
print("-" * 40)
for A in [True, False]:
for B in [True, False]:
A_or_B = A or B
result = A and A_or_B
print(f"{str(A):<5} {str(B):<5} {str(A_or_B):<10} {str(result):<20}")
truth_table()
A B A or B A and (A or B)
----------------------------------------
True True True True
True False True True
False True True False
False False False False
Python Homework 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
def de_morgans_game():
A = random.choice([True, False])
B = random.choice([True, False])
statements = [
f"NOT (A AND B)",
f"NOT (A OR B)"
]
chosen_statement = random.choice(statements)
print(f"Evaluate the following statement based on A = {A} and B = {B}:")
print(f"Expression: {chosen_statement}")
player_input = input("Is the simplified expression True (Yes) or False (No)? ").strip().lower()
if chosen_statement == "NOT (A AND B)":
simplified_result = (not A or not B)
elif chosen_statement == "NOT (A OR B)":
simplified_result = (not A and not B)
Javascript Popcorn Hack 1 Outfit Picker Based on Weather
%%js
function outfitPicker(temp) {
if (temp >= 90) {
console.log("It's really hot! Wear light clothing like shorts and a t-shirt.");
} else if (temp >= 70 && temp < 90) {
console.log("It's warm. Wear something comfortable like jeans and a short-sleeve shirt.");
} else if (temp >= 50 && temp < 70) {
console.log("It's a bit chilly. Wear a light jacket or sweater with long pants.");
} else if (temp >= 30 && temp < 50) {
console.log("It's cold! Wear a coat, sweater, and warm pants.");
} else {
console.log("It's freezing! Wear a heavy coat, gloves, and scarf.");
}
}
let temperature = prompt("Enter the current temperature in Fahrenheit:");
// Convert the input to a number and check if it's valid
temperature = parseFloat(temperature);
if (!isNaN(temperature)) {
outfitPicker(temperature);
} else {
console.log("Please enter a valid number for the temperature.");
}
<IPython.core.display.Javascript object>
Javascript Popcorn Hack 2 Which number is bigger?
%%js
function sortNumbers(numbers) {
numbers.sort(function(a, b) {
return a - b;
});
return numbers;
}
let numbers = prompt("Enter a list of numbers separated by commas (e.g., 5,3,9,1):");
numbers = numbers.split(',').map(Number);
if (numbers.every(isFinite)) {
let sortedNumbers = sortNumbers(numbers);
console.log("Numbers sorted from least to greatest: " + sortedNumbers.join(', '));
} else {
console.log("Please enter valid numbers.");
}
<IPython.core.display.Javascript object>
Javascript Popcorn Hack 3 Even or Odd?
%%js
function isEvenOrOdd(number) {
return number % 2 === 0 ? "Even" : "Odd";
}
const num = 7
console.log(`${num} is ${isEvenOrOdd(num)}`);
<IPython.core.display.Javascript object>
Javascript Homework Hack 1
%%js
function validatePassword(password) {
let isValid = !(password.length < 10 ||
!/[A-Z]/.test(password) ||
!/[a-z]/.test(password) ||
!/\d/.test(password) ||
/\s/.test(password));
return isValid;
}
let password = prompt("Enter your password:");
if (validatePassword(password)) {
console.log("Password is valid!");
} else {
console.log("Password must be at least 10 characters long, include uppercase and lowercase letters, contain at least one number, and have no spaces.");
}
<IPython.core.display.Javascript object>
Javascript Homework Hack 2
%%js
// Simple Personality Quiz
const questions = [
{
question: "1. What is your favorite type of weather?",
options: ["a) Sunny", "b) Rainy", "c) Snowy", "d) Windy"],
answers: { a: "A", b: "B", c: "C", d: "D" }
},
{
question: "2. How do you prefer to spend your free time?",
options: ["a) Reading", "b) Socializing", "c) Sports", "d) Traveling"],
answers: { a: "A", b: "B", c: "C", d: "D" }
},
{
question: "3. What's your ideal vacation?",
options: ["a) Beach", "b) Mountains", "c) City", "d) Countryside"],
answers: { a: "A", b: "B", c: "C", d: "D" }
},
{
question: "4. How do you handle stress?",
options: ["a) Exercise", "b) Meditation", "c) Talk to friends", "d) Distract myself"],
answers: { a: "A", b: "B", c: "C", d: "D" }
},
{
question: "5. What motivates you the most?",
options: ["a) Success", "b) Relationships", "c) Adventure", "d) Knowledge"],
answers: { a: "A", b: "B", c: "C", d: "D" }
},
{
question: "6. How do you make decisions?",
options: ["a) Carefully analyze", "b) Follow my gut", "c) Ask others", "d) Look for excitement"],
answers: { a: "A", b: "B", c: "C", d: "D" }
},
{
question: "7. What's your favorite movie genre?",
options: ["a) Comedy", "b) Drama", "c) Action", "d) Documentary"],
answers: { a: "A", b: "B", c: "C", d: "D" }
},
{
question: "8. How do you approach new challenges?",
options: ["a) Methodically", "b) With enthusiasm", "c) Cautiously", "d) Fearlessly"],
answers: { a: "A", b: "B", c: "C", d: "D" }
},
{
question: "9. What's your preferred social setting?",
options: ["a) Small gatherings", "b) Big parties", "c) One-on-one", "d) Solo"],
answers: { a: "A", b: "B", c: "C", d: "D" }
},
{
question: "10. How do you view change?",
options: ["a) As an opportunity", "b) As a challenge", "c) As unsettling", "d) As a chance to grow"],
answers: { a: "A", b: "B", c: "C", d: "D" }
}
];
function getPersonalityType(answers) {
let scores = { A: 0, B: 0, C: 0, D: 0 };
answers.forEach(answer => {
if (answer in scores) {
scores[answer]++;
}
});
const maxScore = Math.max(scores.A, scores.B, scores.C, scores.D);
const personalityTypes = [];
for (let key in scores) {
if (scores[key] === maxScore) {
personalityTypes.push(key);
}
}
if (personalityTypes.includes("A")) return "You are a thoughtful person.";
if (personalityTypes.includes("B")) return "You are outgoing and enjoy being around others.";
if (personalityTypes.includes("C")) return "You are adventurous and loving.";
if (personalityTypes.includes("D")) return "You are a seeker of knowledge and experiences.";
}
function runQuiz() {
const answers = [];
for (let i = 0; i < questions.length; i++) {
const q = questions[i];
const answer = prompt(`${q.question}\n${q.options.join("\n")}`);
answers.push(answer.toLowerCase());
}
const personalityResult = getPersonalityType(answers);
alert(personalityResult);
}
runQuiz();
<IPython.core.display.Javascript object>