Fall 2024 - P2
Big Idea 3 | .1 | .2 | .3 | .4 | .5 | .6 | .7 | .8 | .10 |
Python Variables
Creating a lesson by using Python.
Popcorn Hack #1
Create a Dictionary of Fruits
Please create a dictionary containing 3 different type of names of fruits as variables, and assign them to numbers 1, 2, and 3. Please print out the output of accessing one value through its corresponding key. Make sure to do it for both javascript
%%js
// Create a dictionary (object) in JavaScript
var myDictionary = {
1: "fruit",
2: "fruit",
3: "fruit"
};
// Accessing a value
console.log("Fruit with key 2:", myDictionary[2]); // Output: fruit
<IPython.core.display.Javascript object>
Popcorn Hack 2
Mini Hack: Math Quiz Game 🎉
Objective
Create a Python math quiz that asks players random math questions (+, -, *) and keeps score.
Steps
- Set Up: Import
random
and define a function,play_game()
. - Generate Questions: In a loop, create two random numbers and an operator.
- Check Answers: Compare the player’s input to the correct answer and update the score.
- Quit Option: Allow the player to type ‘q’ to quit.
- Value change: Change up the values from 1-10 to 1-20
Extra Challenge
Add features like a timer, division questions, or custom messages.
Good luck! 🚀
import random
def play_game():
score = 0
operators = ['+', '-', '*']
print("Welcome to the Math Quiz Game!")
print("Answer as many questions as you can. Type 'q' to quit anytime.\n")
while True:
# Generate two random numbers and choose a random operator
num1 = random.randint(1, 10)
num2 = random.randint(1, 10)
op = random.choice(operators)
# Calculate the correct answer based on the operator
if op == '+':
answer = num1 + num2
elif op == '-':
answer = num1 - num2
else:
answer = num1 * num2
# Ask the player the question
print(f"What is {num1} {op} {num2}?")
player_input = input("Your answer (or type 'q' to quit): ")
# Check if the player wants to quit
if player_input.lower() == 'q':
break
# Check if the answer is correct
try:
player_answer = int(player_input)
if player_answer == answer:
print("Correct!")
score += 1
else:
print(f"Oops! The correct answer was {answer}.")
except ValueError:
print("Invalid input, please enter a number or 'q' to quit.")
print(f"Thanks for playing! Your final score is {score}.")
# Start the game
play_game()
Welcome to the Math Quiz Game!
Answer as many questions as you can. Type 'q' to quit anytime.
What is 1 + 5?
Thanks for playing! Your final score is 0.
Popcorn Hack #3
Temperature Converter
In this hack, you will create a program that converts temperatures between Celsius and Fahrenheit. The program will ask the user for a temperature and the desired conversion direction (Celsius to Fahrenheit or Fahrenheit to Celsius).
Objective:
- Create a temperature converter in both JavaScript and Python.
- Allow users to input a temperature and choose the conversion type.
%%js
// Temperature Converter in JavaScript
let temperature = parseFloat(prompt("Enter the temperature:"));
let conversionType = prompt("Convert to (C)elsius or (F)ahrenheit?").toUpperCase();
if (conversionType === "C") {
// Convert Fahrenheit to Celsius
let celsius = (temperature - 32) * (5 / 9);
console.log(`${temperature}°F is equal to ${celsius.toFixed(2)}°C`);
} else if (conversionType === "F") {
// Convert Celsius to Fahrenheit
let fahrenheit = (temperature * (9 / 5)) + 32;
console.log(`${temperature}°C is equal to ${fahrenheit.toFixed(2)}°F`);
} else {
console.log("Invalid conversion type entered.");
}
<IPython.core.display.Javascript object>
#Python
# Temperature Converter Template
# Function to convert temperatures
def temperature_converter():
try:
# Prompt the user for the temperature
temperature = float(input("Enter the temperature: "))
# Ask the user for the conversion type
conversion_type = input("Convert to Celsius or Fahrenheit? ").strip().upper()
if conversion_type == "C":
pass
# TODO: Convert Fahrenheit to Celsius
# celsius = (temperature - 32) * (5 / 9)
# print(f"{temperature}°F is equal to {celsius:.2f}°C")
elif conversion_type == "F":
pass
# TODO: Convert Celsius to Fahrenheit
# fahrenheit = (temperature * (9 / 5)) + 32
# print(f"{temperature}°C is equal to {fahrenheit:.2f}°F")
else:
print("Invalid conversion type entered. Please enter 'C' or 'F'.")
except ValueError:
print("Invalid input. Please enter a numeric temperature value.")
# Call the temperature converter function
temperature_converter()
Invalid conversion type entered. Please enter 'C' or 'F'.