#Python 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:
# Prompt the user to input a number
num = float(input("Enter a number: "))
# Check if the number is less than 0
if num < 0:
print(f"The number {num} is negative.")
else:
print(f"The number {num} is non-negative.")
except ValueError:
print("Invalid input. Please enter a valid number.")
# Example usage
check_number()
The number -5.0 is negative.
#Python Popcorn Hack 2: Check Scores: Confirms if both scores are at least 70. Output: Prints if the student passed both subjects.
def check_scores():
try:
# Prompt the user to input two scores
score1 = float(input("Enter the score for the first subject: "))
score2 = float(input("Enter the score for the second subject: "))
# Check if both scores are at least 70
if score1 >= 70 and score2 >= 70:
print("The student passed both subjects.")
else:
print("The student did not pass both subjects.")
except ValueError:
print("Invalid input. Please enter valid scores.")
# Example usage
check_scores()
The student did not pass both subjects.
#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():
# Prompt the user to input a character
char = input("Enter a character: ").lower() # Convert input to lowercase for consistency
# Check if the character is a vowel
if len(char) == 1 and char in 'aeiou':
print(f"The character '{char}' is a vowel.")
else:
print(f"The character '{char}' is not a vowel or not a valid input.")
# Example usage
check_vowel()
The character 'b' is not a vowel or not a valid input.
#Python Homework 1: Create a Truth Table: Develop a truth table for a given logical expression.
# Define the table data
cuisine_data = [
{"Cuisine": "Italian", "Common Food Form": "Pizza", "Country of Origin": "Italy"},
{"Cuisine": "Chinese", "Common Food Form": "Noodles", "Country of Origin": "China"},
{"Cuisine": "Mexican", "Common Food Form": "Tacos", "Country of Origin": "Mexico"},
{"Cuisine": "Indian", "Common Food Form": "Curry", "Country of Origin": "India"},
{"Cuisine": "Japanese", "Common Food Form": "Sushi", "Country of Origin": "Japan"},
{"Cuisine": "American", "Common Food Form": "Burger", "Country of Origin": "United States"},
]
# Print the header
print(f"{'Cuisine':<15} {'Common Food Form':<20} {'Country of Origin':<20}")
print("="*55)
# Print the table data
for row in cuisine_data:
print(f"{row['Cuisine']:<15} {row['Common Food Form']:<20} {row['Country of Origin']:<20}")
Cuisine Common Food Form Country of Origin
=======================================================
Italian Pizza Italy
Chinese Noodles China
Mexican Tacos Mexico
Indian Curry India
Japanese Sushi Japan
American Burger United States
#Python Homework 2: Design a Game Using De Morgan’s Law: Create a game that uses De Morgan’s Law to simplify yes or no functions.
def ask_question(question):
while True:
response = input(question + " (yes/no): ").lower()
if response in ["yes", "no"]:
return response == "yes"
else:
print("Please answer with 'yes' or 'no'.")
def play_game():
print("Welcome to the High School Program Game!")
print("To win, you must be in either 11th or 12th grade.")
# Ask the user about their grade
in_ninth_grade = ask_question("Are you in 9th grade?")
in_tenth_grade = ask_question("Are you in 10th grade?")
in_eleventh_grade = ask_question("Are you in 11th grade?")
in_twelfth_grade = ask_question("Are you in 12th grade?")
# Using De Morgan's Law for the win condition:
# You win if you are in either 11th or 12th grade, but not in 9th or 10th.
# Condition: (not in_ninth_grade AND not in_tenth_grade) AND (in_eleventh_grade OR in_twelfth_grade)
if (not in_ninth_grade and not in_tenth_grade) and (in_eleventh_grade or in_twelfth_grade):
print("Congratulations! You win! You're in 11th or 12th grade.")
else:
print("Sorry, you do not qualify. You need to be in 11th or 12th grade.")
# Start the game
play_game()
Welcome to the High School Program Game!
To win, you must be in either 11th or 12th grade.
Congratulations! You win! You're in 11th or 12th grade.
#Python Extra Practice: Checking Divisibility
def is_divisible_by_3_and_5(num):
return num % 3 == 0 and num % 5 == 0
# Test the function
print(is_divisible_by_3_and_5(15)) # True
print(is_divisible_by_3_and_5(10)) # False
#Python Extra Practice: Meal Surprise
def meal_decision(mood, time_of_day):
if mood == "happy" and time_of_day == "morning":
return "Treat yourself with some pancakes!"
elif mood == "tired" and time_of_day == "afternoon":
return "Time for a healthy lunch! Try a chicken salad!"
elif mood == "relaxed" and time_of_day == "evening":
return "Enjoy a nice dinner. Make your own pizza"
else:
return "How about a snack? Have some cheese and crackers"
# Test the function
print(meal_decision("happy", "morning")) # Breakfast
print(meal_decision("tired", "afternoon")) # Lunch
print(meal_decision("relaxed", "evening")) # Dinner
print(meal_decision("stressed", "night")) # Snack
%%js
// JS Popcorn Hack 1: Outfit suggestion based on weather
// Function to suggest an outfit based on temperature
function suggestOutfit() {
// Prompt the user to input the temperature
let temperature = parseFloat(prompt("Enter the temperature (in °C):"));
// Check if the temperature input is a valid number
if (isNaN(temperature)) {
alert("Please enter a valid number for the temperature.");
return;
}
// Outfit suggestions based on temperature ranges using relational and logical operators
if (temperature <= 40) {
alert("Wear a heavy winter coat, scarf, gloves, and boots.");
} else if (temperature > 40 && temperature <= 60) {
alert("Wear a jacket, sweater, and long pants.");
} else if (temperature > 60 && temperature <= 75) {
alert("Wear a light jacket or a sweater, with jeans or casual pants.");
} else if (temperature > 75 && temperature <= 85) {
alert("Wear a t-shirt, shorts, and comfortable shoes.");
} else if (temperature > 88) {
alert("Wear light clothing like tank tops, shorts, and flip-flops.");
} else {
alert("Unable to provide outfit suggestions for this temperature.");
}
}
// Call the function to suggest an outfit
suggestOutfit();
%%js
// JS Popcorn Hack 2: Which number is bigger?
// Function to find the largest number and sort the numbers from least to greatest
function sortNumbersAndFindLargest(numbers) {
// Find the largest number using relational operators
let largest = numbers[0];
for (let i = 1; i < numbers.length; i++) {
if (numbers[i] > largest) {
largest = numbers[i]; // Update largest if current number is greater
}
}
// Sort numbers from least to greatest using the sort() function
// Relational operators are used within the comparison function of sort()
let sortedNumbers = numbers.sort((a, b) => a - b);
// Output the results
console.log("Sorted Numbers (Least to Greatest):", sortedNumbers);
console.log("Largest Number:", largest);
}
// Example list of numbers
let numbers = [12, 45, 7, 20, 3, 99, 56, 32];
// Call the function with the list of numbers
sortNumbersAndFindLargest(numbers);
%%js
// JS Popocorn Hack 3: Even or Odd?
// Function to determine if a number is even or odd
function checkEvenOrOdd() {
// Prompt the user to input a number
let number = parseInt(prompt("Enter a number:"));
// Check if the input is a valid number
if (isNaN(number)) {
alert("Please enter a valid number.");
return;
}
// Use logical operator to check if the number is even or odd
if (number % 2 === 0) {
alert(number + " is an even number.");
} else {
alert(number + " is an odd number.");
}
}
// Call the function to check if the number is even or odd
checkEvenOrOdd();
<IPython.core.display.Javascript object>
%%js
// JS Homework 1: Password Check
function isValidPassword(password) {
// Check password criteria
const hasUppercase = /[A-Z]/.test(password);
const hasLowercase = /[a-z]/.test(password);
const hasNumber = /\d/.test(password);
const hasSpecialChar = /[!@#$%^&*(),.?":{}|<>]/.test(password);
const hasNoSpaces = !/\s/.test(password);
const isLongEnough = password.length >= 10;
// Check for more than 3 consecutive identical characters
const hasConsecutiveChars = /(.)\1\1\1/.test(password); // 4 or more of the same character in a row
// Using De Morgan's Law for the combined condition:
// To be valid, all the following must be true:
// NOT (hasUppercase OR hasLowercase OR hasNumber OR hasSpecialChar OR hasNoSpaces OR !isLongEnough OR hasConsecutiveChars)
// Can be simplified to:
// hasUppercase AND hasLowercase AND hasNumber AND hasSpecialChar AND hasNoSpaces AND isLongEnough AND !hasConsecutiveChars
const isValid = hasUppercase && hasLowercase && hasNumber && hasSpecialChar && hasNoSpaces && isLongEnough && !hasConsecutiveChars;
return isValid;
}
// Function to create a password
function createPassword() {
const password = prompt("Enter your password:");
if (isValidPassword(password)) {
console.log("Your password is valid!");
} else {
console.log("Your password is invalid. Please ensure it meets the following criteria:");
console.log("1. At least 10 characters long.");
console.log("2. Contains both uppercase and lowercase letters.");
console.log("3. Contains at least one number.");
console.log("4. Does not contain any spaces.");
console.log("5. Contains at least 1 special character.");
console.log("6. Contains no more than 3 of the same letter in a row.");
}
}
// Start the password creation process
createPassword();
%%js
// JS Homework 2: Personality Quiz
// Personality quiz data
const quizData = [
{
question: "What do you enjoy doing in your free time?",
options: ["Reading", "Sports", "Cooking", "Watching Movies"],
answer: null
},
{
question: "How do you handle stress?",
options: ["Meditate", "Exercise", "Talk to friends", "Ignore it"],
answer: null
},
{
question: "Which environment do you prefer?",
options: ["Quiet and peaceful", "Busy and energetic", "Creative and artistic", "Structured and organized"],
answer: null
},
{
question: "What kind of music do you enjoy?",
options: ["Classical", "Pop", "Rock", "Jazz"],
answer: null
},
{
question: "How do you make decisions?",
options: ["Go with my gut", "Think it through", "Ask others for input", "Follow the rules"],
answer: null
},
{
question: "What’s your ideal vacation?",
options: ["Beach", "Mountains", "City", "Countryside"],
answer: null
},
{
question: "How do you prefer to communicate?",
options: ["In person", "Texting", "Phone calls", "Emails"],
answer: null
},
{
question: "What motivates you the most?",
options: ["Achievements", "Helping others", "Creativity", "Stability"],
answer: null
},
{
question: "How do you feel about change?",
options: ["Embrace it", "Resist it", "Adapt slowly", "Avoid it"],
answer: null
},
{
question: "How do you view challenges?",
options: ["Opportunities to grow", "Obstacles to overcome", "Stressful situations", "Fun adventures"],
answer: null
}
];
// Function to conduct the quiz
function conductQuiz() {
for (let i = 0; i < quizData.length; i++) {
let question = quizData[i].question;
let options = quizData[i].options;
let answer = prompt(`${question}\n${options.map((option, index) => `${index + 1}. ${option}`).join('\n')}\n\nEnter the number of your answer:`);
// Store the user's answer
if (answer >= 1 && answer <= options.length) {
quizData[i].answer = options[answer - 1];
} else {
alert("Invalid answer. Please try again.");
i--; // Repeat the question
}
}
// Analyze results
analyzeResults();
}
// Function to analyze results and determine personality type
function analyzeResults() {
let personalityType = { introvert: 0, extrovert: 0, thinker: 0, feeler: 0 };
quizData.forEach(q => {
switch (q.answer) {
case "Reading":
case "Meditate":
case "Quiet and peaceful":
case "Classical":
case "Think it through":
case "Countryside":
personalityType.introvert++;
break;
case "Sports":
case "Exercise":
case "Busy and energetic":
case "Pop":
case "Ask others for input":
case "Beach":
personalityType.extrovert++;
break;
case "Creative and artistic":
case "Jazz":
case "Follow the rules":
case "Opportunities to grow":
personalityType.thinker++;
break;
case "Talk to friends":
case "Ignore it":
case "Structured and organized":
case "Stressful situations":
personalityType.feeler++;
break;
default:
break;
}
});
// Determine the dominant personality type
let dominantType = Object.keys(personalityType).reduce((a, b) => personalityType[a] > personalityType[b] ? a : b);
// Output personality description based on dominant type
switch (dominantType) {
case "introvert":
alert("You are an Introvert! You enjoy solitary activities and prefer quiet environments. You value deep connections with a few people.");
break;
case "extrovert":
alert("You are an Extrovert! You thrive in social settings and enjoy being active. You find energy in interactions with others.");
break;
case "thinker":
alert("You are a Thinker! You are analytical and prefer to make decisions based on logic. You enjoy creative and artistic pursuits.");
break;
case "feeler":
alert("You are a Feeler! You are empathetic and prioritize emotional connections. You care deeply about others' feelings.");
break;
default:
alert("You have a unique personality that doesn't fit into one category!");
break;
}
}
// Start the quiz
conductQuiz();
%%js
// JS Extra Practice: Old enough to vote?
function canVote(age) {
return age >= 18;
}
// Test the function
console.log(canVote(20)); // true
console.log(canVote(16)); // false
%%js
// JS Extra Practice: Uppercase?
function isFirstCharUppercase(str) {
return str[0] === str[0].toUpperCase();
}
// Test the function
console.log(isFirstCharUppercase("Hello")); // true
console.log(isFirstCharUppercase("world")); // false