Skip to the content.

Sprint2a Popcornhacks_ipynb_2_

%%js
// HW 1 FIRST SECTION JV

const bobs = {
    "first": "bob1",
    "second": "bob2"
}

for (const key in bobs) {
    console.log(key + ": " + bobs[key])
}
<IPython.core.display.Javascript object>
%%js
//POP 1 FIRST SECTION

for (let i = 0; i < 5; i++) {
    console.log(i);
}
<IPython.core.display.Javascript object>
# POP 2 FIRST SECTION
structures = ['🗿', '🏛', '🛳']
for structure in structures:
    print(structure)
🗿
🏛
🛳
//POP 2 FIRST SECTION
%%javascript
const names = ['bob', 'joe', 'smith'];

for (let i = 0; i < names.length; i++) {
    console.log(names[i]);
}
<IPython.core.display.Javascript object>
# POP 1 SECOND SECTION
number = 1

while number <= 20:
    if number % 2 == 1:
        print(number)
    number += 1
1
3
5
7
9
11
13
15
17
19
# POP 2 SECOND SECTION
import random

flip = ""

while flip != "tails":
    flip = random.choice(["heads", "tails"])
    print(f"Flipped: {flip}")

print("Landed on tails!")
Flipped: tails
Landed on tails!
# HW 1 SECTION 2
'''
Print numbers from 1 to 50.
For multiples of 3, print “Fizz” instead of the number.
For multiples of 5, print “Buzz” instead of the number.
For numbers divisible by both 3 and 5, print “FizzBuzz”.
Add a twist: for multiples of 7, print “Boom”.
'''
i = 1
while i < 51:
    if i % 3 == 0:
        if i % 5 == 0:
            print("FizzBuzz")
        elif i % 7 == 0:
            print("Boom")
        else:
            print("Fizz")
    elif i % 5 == 0:
        if i % 3 == 0:
            print("FizzBuzz")
        else:
            print("Buzz")
    elif i % 7 == 0:
            print("Boom")
    else:
        print(i)
    i += 1
1
2
Fizz
4
Buzz
Fizz
Boom
8
Fizz
Buzz
11
Fizz
13
Boom
FizzBuzz
16
17
Fizz
19
Buzz
Boom
22
23
Fizz
Buzz
26
Fizz
Boom
29
FizzBuzz
31
32
Fizz
34
Buzz
Fizz
37
38
Fizz
Buzz
41
Boom
43
44
FizzBuzz
46
47
Fizz
Boom
Buzz
# HW 2 SECTION 2
'''
The user has 3 attempts to enter the correct username and password.
After each failed attempt, display how many attempts are left.
After 3 failed attempts, display a message saying the account is locked.
Use a do-while loop to handle the login process, prompting the user for their credentials until they either succeed or run out of attempts.
'''

username = "bobski123"
password = "12345"
wrong_counter = 3

while wrong_counter > 0:
    user = input("Enter the username buddy: ")
    psd = input("Enter passcode or i will come to ur house and find you: ")
    
    if user != username or psd != password:
        print("Faild Attempt you bad bad person")
        print("Amount of times you brain is bad again:", wrong_counter - 1)
    else:
        print("good job bringing out your inner indian scammer vibes")
    




good job bringing out your inner indian scammer vibes
Faild Attempt you bad bad person
Amount of times you brain is bad again: 2
Faild Attempt you bad bad person
Amount of times you brain is bad again: 2
Faild Attempt you bad bad person
Amount of times you brain is bad again: 2
Faild Attempt you bad bad person
Amount of times you brain is bad again: 2



---------------------------------------------------------------------------

KeyboardInterrupt                         Traceback (most recent call last)

Cell In[57], line 15
     13 while wrong_counter > 0:
     14     user = input("Enter the username buddy: ")
---> 15     psd = input("Enter passcode or i will come to ur house and find you: ")
     17     if user != username or psd != password:
     18         print("Faild Attempt you bad bad person")


File ~/nighthawk/student_2025/venv/lib/python3.12/site-packages/ipykernel/kernelbase.py:1282, in Kernel.raw_input(self, prompt)
   1280     msg = "raw_input was called, but this frontend does not support input requests."
   1281     raise StdinNotImplementedError(msg)
-> 1282 return self._input_request(
   1283     str(prompt),
   1284     self._parent_ident["shell"],
   1285     self.get_parent("shell"),
   1286     password=False,
   1287 )


File ~/nighthawk/student_2025/venv/lib/python3.12/site-packages/ipykernel/kernelbase.py:1325, in Kernel._input_request(self, prompt, ident, parent, password)
   1322 except KeyboardInterrupt:
   1323     # re-raise KeyboardInterrupt, to truncate traceback
   1324     msg = "Interrupted by user"
-> 1325     raise KeyboardInterrupt(msg) from None
   1326 except Exception:
   1327     self.log.warning("Invalid Message:", exc_info=True)


KeyboardInterrupt: Interrupted by user

3.3

# POP 1 SECTION THREE
tasks = [
    "Study Chem",
    "Study math",
    "Almost forgetting world",
    "eating cereal",
    "pat nikhil aggresivley on the back"
]

# Function to display tasks with indices
def display_tasks():
    print("Your To-Do List:")
    for index in range(len(tasks)):
        print(f"{index + 1}. {tasks[index]}")  # Display task with its index

# Call the function
display_tasks()
Your To-Do List:
1. Study Chem
2. Study math
3. Almost forgetting world
4. eating cereal
5. pat nikhil aggresivley on the back
// POP 1 SECTION THREE 
%%javascript
// List of tasks
const tasks = [
    "Study Chem",
    "Study math",
    "Almost forgetting world",
    "eating cereal",
    "pat nikhil aggresivley on the back"
];

// Function to display tasks with indices
function displayTasks() {
    console.log("Your To-Do List:");
    for (let index = 0; index < tasks.length; index++) {
        console.log(`${index + 1}. ${tasks[index]}`); // Display task with its index
    }
}

// Call the function
displayTasks();
<IPython.core.display.Javascript object>

3.4

// POP 1 SECTION FOUR 

%%javascript
for (let i = 0; i < 10; i++)
  for (let i = 0; i < 10; i++) {
    if (i === 5) {
        break;
    }
    console.log(i);
}
for i in range (1, 20):
    if i % 2 == 0:
        continue
    if i % 2 == 1:
        print(i, "odd")
    if i == 17:
        break
1 odd
3 odd
5 odd
7 odd
9 odd
11 odd
13 odd
15 odd
17 odd
%% js
// HW 1 SECTION 4
for (let i = 0; i <= 10; i += 2) {
    console.log(i);
    if (i === 6) {
        break;
    }
}

UsageError: Cell magic `%%` not found.
# HW 2 SECTION 4
for i in range(10):
    if i % 2 == 0:
        continue
    print(f"This number is {i}")

This number is 1
This number is 3
This number is 5
This number is 7
This number is 9

3.10

# POP 1 SECTION 1
print("Adding Numbers In List Script")
print("-"*25)
numlist = [4, 5]
while True:
    start = input("Would you like to (1) enter numbers (2) add numbers (3) remove last value added or (4) exit: ")
    if start == "1":
        val = input("Enter a numeric value: ") # take input while storing it in a variable
        try: 
            test = int(val) # testing to see if input is an integer (numeric)
        except:
            print("Please enter a valid number")
            continue # 'continue' keyword skips to next step of while loop (basically restarting the loop)
        numlist.append(int(val)) # append method to add values
        print("Added "+val+" to list.")
    elif start == "2":
        sum = 0
        for num in numlist: # loop through list and add all values to sum variable
            sum += num
        print("Sum of numbers in list is "+str(sum))
    elif start == "3":
        if len(numlist) > 0: # Make sure there are values in list to remove
            print("Removed "+str(numlist[len(numlist)-1])+" from list.")
            numlist.pop()
        else:
            print("No values to delete")
    elif start == "4":
        break # Break out of the while loop, or it will continue running forever
    else:
        continue
Adding Numbers In List Script
-------------------------
Sum of numbers in list is 9
# HW 1 SECTION 1

mylist = ["apple", "orange", "banana"]

print("Current list:", mylist)

index = int(input("Enter an index to remove an item (0 for 'apple', 1 for 'orange', 2 for 'banana'): "))

removed_item = mylist.remove(mylist[index])

print("Updated list:", mylist)
Current list: ['apple', 'orange', 'banana']
Updated list: ['orange', 'banana']

POP 1 SECTION 2

nums ← 1 to 100 odd_sum ← 0

for each num in nums: if num % 2 is 0: odd_sum ← odd_sum + num

print(“Sum of odd numbers:”, odd_sum)

# EXAMPLE
def find_max_min(numbers):
    if not numbers:
        return None, None  # <span style="color: #D9B68C;">Return None if the list is empty</span>
    
    max_num = numbers[0]  # <span style="color: #D9B68C;">Start with the first number as the max</span>
    min_num = numbers[0]  # <span style="color: #D9B68C;">Start with the first number as the min</span>
    
    for num in numbers:
        if num > max_num:
            max_num = num  # <span style="color: #D9B68C;">Update max if a larger number is found</span>
        if num < min_num:
            min_num = num  # <span style="color: #D9B68C;">Update min if a smaller number is found</span>
            
    return max_num, min_num  # <span style="color: #D9B68C;">Return the found max and min</span>

# Example usage
numbers = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5]
max_num, min_num = find_max_min(numbers)

print(f"\033[92mMaximum number: {max_num}\033[0m")  # Bright green for output
print(f"\033[92mMinimum number: {min_num}\033[0m")  # Bright green for output
Maximum number: 9
Minimum number: 1
# HW 1 SECTION 2

'''
numbers ← list of 30 numbers (1, 2, 3, ..., 30)
even_sum ← 0
odd_sum ← 0

for each number in numbers:
    if number % 2 is 0:
        even_sum ← even_sum + number
    else:
        odd_sum ← odd_sum + number

print "Sum of even numbers:", even_sum
print "Sum of odd numbers:", odd_sum

'''

# PYTHON VERSION

numbers = list(range(1, 31))

even_sum = 0
odd_sum = 0

for number in numbers:
    if number % 2 == 0:
        even_sum += number
    else:
        odd_sum += number

print("Sum of even numbers:", even_sum)
print("Sum of odd numbers:", odd_sum)


Sum of even numbers: 240
Sum of odd numbers: 225
#POP 1 SECTION 3

import random

# Define main dishes and sides
main_dishes = ['Nikhil', 'Rohan']
sides = ['weird', 'cool']

# Create meal combinations using list comprehension
meal_combinations = [f"{main} is {side}" for main in main_dishes for side in sides]

# Print a random meal combination
print(random.choice(meal_combinations))
Nikhil is weird
# HW 1 SECTION 3


hobbies = ["Skiing", "Basketball", "Coding", "Cooking", "Gaming"]

# Loop through each hobby and print it
for hobby in hobbies:
    print("One of my favorite hobbies is: ", hobby)

One of my favorite hobbies is:  Skiing
One of my favorite hobbies is:  Basketball
One of my favorite hobbies is:  Coding
One of my favorite hobbies is:  Cooking
One of my favorite hobbies is:  Gaming
# EXAMPLE SECTION 4

people = []

# Function to collect user input and create a person object
def add_person():
    name = input("What is your name? ")
    age = input("How old are you? ")
    gender = input("What is ur gender ")
    ethnicity = input("What is ur  ")
    
    # Simple Yes/No question for student status
    while True:
        is_student = input("Are you a student? (yes/no): ").lower()
        if is_student in ["yes", "no"]:
            is_student = (is_student == "yes")  # Converts to Boolean
            break
        else:
            print("Please enter 'yes' or 'no'.")

    # Create the person object
    person = {
        'name': name,
        'age': age,
        'is_student': is_student
    }
    
    # Add the person to the list
    people.append(person)

    # Display the added person
    display_people()

# Function to display the list of people
def display_people():
    print("\nCurrent List of People:")
    for index, person in enumerate(people, 1):
        student_status = "a student" if person['is_student'] else "not a student"
        print(f"Person {index}: {person['name']}, {person['age']} years old, {student_status}")

# Example Usage
add_person()  # Call this to start collecting input from the user

# HW 1 SECTION 4

questions = ["Do you like Python?", "Are you learning programming?"]
answers = [] 


for question in questions:
    answer = input(f"{question} (yes/no): ")
    answers.append(answer)

for i in range(len(questions)):
    print(f"Question: {questions[i]}")
    print(f"Your answer: {answers[i]}")
Question: Do you like Python?
Your answer: yes
Question: Are you learning programming?
Your answer: yes

3.1

%%js
// POP 1

var myDictionary = {
    1: "bob",
    2: "boy",
    3: "mihir"
};

console.log("Key 3:", myDictionary[3]);
<IPython.core.display.Javascript object>
# POP 2

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 10 - 10?
Invalid input, please enter a number or 'q' to quit.
What is 3 * 10?
Correct!
What is 4 - 3?
Correct!
What is 3 + 6?
Correct!
What is 7 + 4?
Correct!
What is 4 + 3?
Correct!
What is 9 - 7?
Correct!
What is 6 * 9?
Correct!
What is 5 * 6?
Correct!
What is 2 * 7?
Correct!
What is 8 + 6?
Correct!
What is 5 + 1?
Correct!
What is 5 * 7?
Oops! The correct answer was 35.
What is 2 * 3?
Correct!
What is 7 * 3?
Correct!
What is 7 * 8?
Correct!
What is 5 * 6?
Correct!
What is 3 * 5?
Oops! The correct answer was 15.
What is 1 * 7?
Correct!
What is 8 - 10?
Invalid input, please enter a number or 'q' to quit.
What is 4 + 7?
Invalid input, please enter a number or 'q' to quit.
What is 8 * 2?
Invalid input, please enter a number or 'q' to quit.
What is 1 - 2?
Invalid input, please enter a number or 'q' to quit.
What is 2 - 5?
Invalid input, please enter a number or 'q' to quit.
What is 2 - 2?
Invalid input, please enter a number or 'q' to quit.
What is 3 - 6?
Invalid input, please enter a number or 'q' to quit.
What is 4 - 4?
Thanks for playing! Your final score is 16.
%%js
// POP 3

// 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>
# POP 3
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
            celsius = (temperature - 32) * (5 / 9)
            print(f"{temperature}°F is equal to {celsius:.2f}°C")

        elif conversion_type == "F":
            pass
            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'.
# HW 1
shopping_list = []
cost = 0

while True:
    user_item = input("Enter item: ")
    item_cost = int(input("Enter cost: "))
    shopping_list.append((user_item, item_cost))
    cost += item_cost
    continue_user = int(input("Contine, 1 for yes, 0 for no"))
    if continue_user == 1:
        pass
    else:
        break
%%js 
// HW 2

const conversionRates = {
    cupsToTablespoons: 16,
    tablespoonsToTeaspoons: 3,
    cupsToTeaspoons: 48,
};

function convert(quantity, fromUnit, toUnit) {
    let convertedQuantity;

    if (fromUnit === "cups" && toUnit === "tablespoons") {
        convertedQuantity = quantity * conversionRates.cupsToTablespoons;
    } else if (fromUnit === "tablespoons" && toUnit === "teaspoons") {
        convertedQuantity = quantity * conversionRates.tablespoonsToTeaspoons;
    } else if (fromUnit === "cups" && toUnit === "teaspoons") {
        convertedQuantity = quantity * conversionRates.cupsToTeaspoons;
    } else {
        return "Conversion not supported!";
    }
    
    return convertedQuantity;
}

let ingredients = [];
let continueInput = true;

while (continueInput) {
    let ingredient = {};
    
    ingredient.name = prompt("Enter the ingredient name:");
    
    ingredient.quantity = parseFloat(prompt(`Enter the quantity for ${ingredient.name}:`));
    ingredient.fromUnit = prompt("Enter the unit of this quantity (cups/tablespoons/teaspoons):");
    ingredient.toUnit = prompt("Enter the unit you want to convert to (cups/tablespoons/teaspoons):");

    ingredient.convertedQuantity = convert(ingredient.quantity, ingredient.fromUnit, ingredient.toUnit);

    ingredients.push(ingredient);
    
    let userResponse = prompt("Do you want to add another ingredient? (yes/no):");
    continueInput = (userResponse.toLowerCase() === "yes");
}

console.log("Converted Ingredient Quantities:");
ingredients.forEach((ingredient) => {
    console.log(`${ingredient.quantity} ${ingredient.fromUnit} of ${ingredient.name} is equivalent to ${ingredient.convertedQuantity} ${ingredient.toUnit}`);
});
<IPython.core.display.Javascript object>

3.4

%%js
// POP 1

let favoriteMovie = "Top Gun";
let favoriteSport = "Badminton";
let petName = "Nikhil";

let concatenatedMessage = "My favorite movie is " + favoriteMovie + ". I love playing " + favoriteSport + " and my pet's name is " + petName + ".";

let interpolatedMessage = `My favorite movie is ${favoriteMovie}. I love playing ${favoriteSport} and my pet's name is ${petName}.`;
<IPython.core.display.Javascript object>
%%js
// POP 2

let phrase = "Nikhil likes biryani and curry";

let partOne = phrase.slice(2, 8);
let partTwo = phrase.slice(-18, -12);
let remainder = phrase.slice(20);

console.log(partOne);
console.log(partTwo);
console.log(remainder);
<IPython.core.display.Javascript object>
#POP 3

def remove_vowels(input_str):
    vowels = "aeiouAEIOU"
    result = ''.join([char for char in input_str if char not in vowels])
    return result

sentence = input("Enter sentence")
print(remove_vowels(sentence))
H chnky mnky
# POP 4

def reverse_words(input_str):
    words = input_str.split()
    reversed_words = " ".join(words[::-1])
    return reversed_words

sentence1 = input("Enter sentence")
print(reverse_words(sentence1))
sentence2 = input("Enter sentence")
print(reverse_words(sentence2))
sentence3 = input("Enter sentence")
print(reverse_words(sentence3))
bob hi
mom hi
boy stupid the aturi m nikhil hi
%%js
// HW 1

let firstName = prompt("Enter your first name: ");
let lastName = prompt("Enter your last name: ");


let message = "Greetings" + firstName + lastName +  ".";
console.log(message);
<IPython.core.display.Javascript object>
# HW 2
'''
def palindrome(input_str):
    clean_str = input_str.replace(" ", "").lower()
    
    return clean_str == clean_str[::-1]
input = input('Enter word')
print(palindrome(input))
'''

string = input('Enter a word: ')
rev_letters = []

for letter in string:
    rev_letters.append(letter)

result = "".join(rev_letters[::-1])

if string == result:
    print('palindrome')
else:
    print('Aiyaaaaa make a proper palindrome')
    
Aiyaaaaa make a proper palindrome

3.3

# POP 1

a = int(input("Enter first num: "))
b = int(input("Enter second num: "))

print(f"Add: ", (a+b))
print(f"Subtract: ", (a-b))
print(f"Multiply: ", (a*b))
print(f"Divide: ", (a/b))
Add:  5
Subtract:  -1
Multiply:  6
Divide:  0.6666666666666666
# POP 2

def fibonacci(n):
    if n == 1:
        return 0
    elif n == 2:
        return 1
    else:
        return fibonacci(n - 1) + fibonacci(n - 2)


n = int(input("Enter the nth number for the Fibonacci sequence: "))
print(f"The {n}th Fibonacci number is: {fibonacci(n)}")
The 4th Fibonacci number is: 2
# HW 1

import numpy as np
import logging
import sys

# Configure logging
logging.basicConfig(level=logging.INFO, format='%(levelname)s:%(message)s')

def matrix_multiply(A, B):
    """
    Perform matrix multiplication between two numpy arrays A and B.
    """
    logging.debug(f"Multiplying matrices:\n{A}\n{B}")
    return np.dot(A, B)

def matrix_power(M, power):
    """
    Raise matrix M to the specified power using binary exponentiation.
    """
    if power < 0:
        raise ValueError("Power must be a non-negative integer.")
    
    result = np.identity(len(M), dtype=object)
    logging.debug(f"Initial identity matrix:\n{result}")
    
    while power > 0:
        if power % 2 == 1:
            result = matrix_multiply(result, M)
            logging.debug(f"Result after multiplying by M:\n{result}")
        M = matrix_multiply(M, M)
        logging.debug(f"Matrix M squared:\n{M}")
        power = power // 2
        logging.debug(f"Power reduced to: {power}")
    
    return result

def fibonacci_matrix(n):
    """
    Calculate the nth Fibonacci number using matrix exponentiation.
    """
    if not isinstance(n, int):
        raise TypeError("Input must be an integer.")
    if n < 0:
        raise ValueError("Fibonacci number is not defined for negative integers.")
    elif n == 0:
        return 0
    elif n == 1:
        return 1
    
    F = np.array([[1, 1],
                  [1, 0]], dtype=object)
    
    result = matrix_power(F, n-1)
    
    logging.info(f"Matrix raised to power {n-1}:\n{result}")
    
    return result[0][0]

def validate_input(user_input):
    """
    Validate the user input to ensure it's a non-negative integer.
    """
    try:
        value = int(user_input)
        if value < 0:
            raise ValueError
        return value
    except ValueError:
        raise ValueError("Please enter a valid non-negative integer.")

def main():
    """
    Main function to execute the Fibonacci calculation.
    """
    try:
        user_input = input("Enter the position of the Fibonacci number you want to calculate: ")
        n = validate_input(user_input)
        fib_n = fibonacci_matrix(n)
        print(f"Fibonacci number at position {n} is: {fib_n}")
    except ValueError as ve:
        logging.error(ve)
    except Exception as e:
        logging.error(f"An unexpected error occurred: {e}")
        sys.exit(1)

if __name__ == "__main__":
    main()
---------------------------------------------------------------------------

ModuleNotFoundError                       Traceback (most recent call last)

Cell In[39], line 3
      1 # HW 1
----> 3 import numpy as np
      4 import logging
      5 import sys


ModuleNotFoundError: No module named 'numpy'

3.5

# POP 1
def A():
    return "I got punched"  # Condition A

def B():
    return "I am bruised"  # Condition B

# Original statement: if A then B
if A():
    print("I was punched, so ", B())
else:
    print("I did not get punched,  so we cannot conclude anything about getting bruised.")

# Contrapositive: if not B then not A
if not B():
    print("I was not brused, therefore I was not: ", A())
else:
    print("I was burised, but we dont know if I was punched.")
I was punched, so  I am bruised
I was burised, but we dont know if I was punched.
%%js
// POP 1 JAVA VERSIOM

function A() {
    return true; // Condition A
}

function B() {
    return true; // Condition B
}

// Main function
function main() {
    // Original statement: if A then B
    if (A()) {
        console.log("A is true, so B must also be true: " + B());
    } else {
        console.log("A is false, we cannot conclude anything about B.");
    }
    
    // Contrapositive: if not B then not A
    if (!B()) {
        console.log("B is false, therefore A must also be false: " + !A());
    } else {
        console.log("B is true, we cannot conclude anything about A.");
    }
}

// Call the main function to run the code
main();

<IPython.core.display.Javascript object>
# HW 1

def AND(A, B):
    return A and B

def OR(A, B):
    return A or B

def NOT(A):
    return not A

print("A     B | AND | OR | NOT A")
print("---------------------------")
for A in [True, False]:
    for B in [True, False]:
        print(f"{A:<5} {B:<5} | {AND(A, B):<4} | {OR(A, B):<3} | {NOT(A)}")
A     B | AND | OR | NOT A
---------------------------
1     1     | 1    | 1   | False
1     0     | 0    | 1   | False
0     1     | 0    | 1   | True
0     0     | 0    | 0   | True
%% js
// HW 2
// It is suppsoed to be javascript but code is in java, so output does not work.



class LogicGateSimulator {

    // Define logic gate functions
    static AND(A, B) {
        return A && B;
    }

    static OR(A, B) {
        return A || B;
    }

    static NOT(A) {
        return !A;
    }

    static NAND(A, B) {
        return !(A && B);
    }

    static NOR(A, B) {
        return !(A || B);
    }

    static XOR(A, B) {
        return A ^ B;
    }

    // Display the results of the logic gates
    static displayGateOperations(A, B) {
        console.log(`A: ${A}, B: ${B}`);
        console.log(`AND: ${LogicGateSimulator.AND(A, B)}`);
        console.log(`OR: ${LogicGateSimulator.OR(A, B)}`);
        console.log(`NOT A: ${LogicGateSimulator.NOT(A)}`);
        console.log(`NAND: ${LogicGateSimulator.NAND(A, B)}`);
        console.log(`NOR: ${LogicGateSimulator.NOR(A, B)}`);
        console.log(`XOR: ${LogicGateSimulator.XOR(A, B)}`);
        console.log("-----------------------------");
    }

    static main() {
        const readline = require('readline').createInterface({
            input: process.stdin,
            output: process.stdout
        });

        console.log("Logic Gate Simulator");
        console.log("Enter 'exit' to quit");

        const askQuestions = () => {
            readline.question("Enter value for A (true/false): ", (A_input) => {
                if (A_input.toLowerCase() === "exit") {
                    readline.close();
                    return;
                }

                readline.question("Enter value for B (true/false): ", (B_input) => {
                    if (B_input.toLowerCase() === "exit") {
                        readline.close();
                        return;
                    }

                    // Convert inputs to boolean
                    const A = (A_input.toLowerCase() === 'true');
                    const B = (B_input.toLowerCase() === 'true');

                    // Display the results
                    LogicGateSimulator.displayGateOperations(A, B);
                    askQuestions();
                });
            });
        };

        askQuestions();
    }
}

LogicGateSimulator.main();


UsageError: Cell magic `%%` not found.

3.6

# POP 1

x = 200

if x % 10 == 0:
    print("no remainder after divided by 10")
else:
    print("remainde after 10")
no remainder after divided by 10
%%js
// POP 1

let x = 200;

// Conditional statement
if (x % 10 == 0) {
    console.log("no remainder after divided by 10");
} else {
    console.log("remainde after 10");
}
<IPython.core.display.Javascript object>
# POP 2

isHuman = True

if isHuman:
    print("Not alien")
else:
    print("Alien")
Not alien
%%js
// POP 2

let isHuman = true;

if (isHuman) {
    console.log("Not alien");
} else {
    console.log("Alien");
}
<IPython.core.display.Javascript object>
# POP 3
import random

value = random.randint(1, 10)
print(value)

if value >= 5:
    if value % 2 == 0:
        print("greater or equal to five, divisbile by two")
    else:
        print("greater or equal to five, not divisble by 2")
else:
    if value % 2 == 0:
        print("less that five, divisbile by two")
    else:
        print("less that 5, not divisble by 2")
    

5
greater or equal to five, not divisble by 2
%%js
// POP 3

const value = Math.floor(Math.random() * 10) + 1;
console.log(value);

if (value >= 5) {
    if (value % 2 === 0) {
        console.log("greater or equal to five, divisible by two");
    } else {
        console.log("greater or equal to five, not divisible by 2");
    }
} else {
    if (value % 2 === 0) {
        console.log("less than five, divisible by two");
    } else {
        console.log("less than 5, not divisible by 2");
    }
}
<IPython.core.display.Javascript object>
# HW 1

correct_ans = 0
wrong_ans = 0

q1 = input("What is the capital of Russia: ").lower()
if q1 == "moscow":
    print('DING DING DING')
    correct_ans += 1
else:
    print("WHY WHY WHY")
    wrong_ans += 1

q2 = input("What is the capital of France: ").lower()
if q2 == "paris":
    print('DING DING DING')
    correct_ans += 1
else:
    print("WHY WHY WHY")
    wrong_ans += 1

q3 = input("What is the capital of Germany: ").lower()
if q3 == "berlin":
    print('DING DING DING')
    correct_ans += 1
else:
    print("WHY WHY WHY")
    wrong_ans += 1
    
q4 = input("What is the capital of South Korea: ").lower()
if q4 == "seoul":
    print('DING DING DING')
    correct_ans += 1
else:
    print("WHY WHY WHY")
    wrong_ans += 1

q5 = input("What is the capital of Australia: ").lower()
if q5 == "canaberra":
    print('DING DING DING')
    correct_ans += 1
else:
    print("WHY WHY WHY")
    wrong_ans += 1

q6 = input("What is the capital of Rohan: ").lower()
if q6 == "r":
    print('DING DING DING')
    correct_ans += 1
else:
    print("WHY WHY WHY")
    wrong_ans += 1
    
print("Num of wrong: ", wrong_ans)
print("Num of correct: ", correct_ans)
DING DING DING
DING DING DING
DING DING DING
DING DING DING
WHY WHY WHY
DING DING DING
Num of wrong:  1
Num of correct:  5

3.7

# POP 1
age = int(input("Enter age: "))
likes_sweets = int(input("Do you like sweets? (yes = 1/no = 0): "))

if age >= 10:
    if likes_sweets == 1:
        print("You can have chocolate!")
    else:
        print("get some salad...")
else:
    print("You get a welch gummy bears.")
You get a welch gummy bears.
%%js
// POP 1

age = 5;
likes_sweets = Number(input('Do you like sweets? (yes = 1/no = 0): '));

if (age >= 10) {
    if (likes_sweets == 1) {
        console.log('You can have chocolate!');
    } else {
        console.log('get some salad...');
} else {
    console.log('You get a welch gummy bears.');

    }
}
<IPython.core.display.Javascript object>
# POP 2

# Savings
total = 500  

# Laptop prices
tomato = 800
potato = 700
nikhil = 100

# Determine which laptop you can buy
if total >= tomato:
    print("You can buy a tomato")
elif total >= potato:
    print("You can buy a potato")
elif total >= nikhil:
    print("You can buy a nikhil")
else:
    print("You don't have enough money to buy a laptop.")
You can buy a nikhil
%%js
// POP 3


let store_open = true;
let vegetables_available = false;

if (store_open) {
    console.log("You can go shopping. YAYYYY.");

    if (vegetables_available) {
        console.log("Buy vegetables.");
    } else {
        console.log("Check for other items instead.");
    }
} else {
    console.log("The store is closed, go away.");
}
<IPython.core.display.Javascript object>
# HW 1

user_age = int(input("Enter your age: "))
user_ball = int(input("Do you have a ball (yes = 1, no = 2): "))

if user_age >= 5 and user_ball == 1:
    print("verfied to be greater than 5")
    if user_age >= 8:
        print("play with older kids")
    else:
        print("play with younger kids")
else:
    print("cant join games")
verfied to be greater than 5
play with younger kids

Project

# Running From The Mongols
import sys
import random

health = 100
experience = 0

print("Hello explored traveler!")
print("My name is Ivan I, prince of the Rus, in 13th century. These lands have been torn down and broken apart by the Mongols, please, do something!")
print("As you help prevent and defend attacks from the Mongols, your stats change: health: ", health, ", experience: ", experience)

ans1 = input("Are you ready for the journey? (yes/no): ").lower()
if ans1 != "yes":
    sys.exit()
    
print("Now it's time to choose your main weapon!")

# Weapon Dictionary values for each key: index 0: damage, index 1: attack distance
weapon_dict = {
    "Sword": [25, 10],
    "Bow_Arrow": [20, 40],
    "Spear": [50, 5]
}

# List of catchphrases
catchphrases = ["Bam!", "Slash!", "Hit!", "Smack!", "Strike!", "Wham!"]

while True:
    learning_weapons = input("Let's look at the different types of weapons, the Sword(0), the Bow and Arrow(1), and the Spear(2). Type 3 to stop: ")
    
    if learning_weapons == '0':
        print("Good choice, a sword is used in closer combat. The damage it can deal is ", weapon_dict["Sword"][0], ", and its attack distance is", weapon_dict["Sword"][1])
    elif learning_weapons == '1':
        print("Good choice, a bow and arrow is used in longer range combat. The damage it can deal is ", weapon_dict["Bow_Arrow"][0], ", and its attack distance is", weapon_dict["Bow_Arrow"][1])
    elif learning_weapons == '2':
        print("Good choice, a spear is used in very close combat. The damage it can deal is ", weapon_dict["Spear"][0], ", and its attack distance is", weapon_dict["Spear"][1])
    elif learning_weapons == '3':
        break
    else:
        print("Invalid input. Please choose a valid weapon or type 3 to stop.")

main_weapon = input("So which one do you choose: 0 for sword, 1 for bow and arrow, and 2 for spear: ")


print("10 years later ....")
print("OH NO, GENGHIS KHAN IS ATTACKING!")
print("DEPLOY ALL FORCES")


'''
Peusdocode for function strucutre:

define combat method (parameters are distance and health):
    if the distance of the enemy is <= weapon distance:
        while the enemy health is > 0:
            print random catchphrase
            Subtract from enemy health with weapon damage
        print enemy is defeated
    else:
        print the enemy is too far away
'''

def take_damage(player_health, missed_shots):
    player_health -= missed_shots * 10
    print("You missed ", missed_shots, "times! Your health is now: ", player_health)
    return player_health

def sword_combat(distance_to_enemy, enemy_health, player_health, missed_shots):
    if distance_to_enemy <= weapon_dict["Sword"][1]:
        while enemy_health > 0:
            print(random.choice(catchphrases))
            enemy_health -= weapon_dict["Sword"][0]
        print("Enemy defeated with the sword!")
    else:
        print("The enemy is too far for a sword attack.")
        missed_shots += 1
        player_health = take_damage(player_health, missed_shots)
    return player_health, missed_shots

def bow_arrow_combat(distance_to_enemy, enemy_health, player_health, missed_shots):
    if distance_to_enemy <= weapon_dict["Bow_Arrow"][1]:
        while enemy_health > 0:
            print(random.choice(catchphrases))
            enemy_health -= weapon_dict["Bow_Arrow"][0]
        print("Enemy defeated with the bow and arrow!")
    else:
        print("The enemy is too far for a bow and arrow attack.")
        missed_shots += 1
        player_health = take_damage(player_health, missed_shots)
    return player_health, missed_shots

def spear_combat(distance_to_enemy, enemy_health, player_health, missed_shots):
    if distance_to_enemy <= weapon_dict["Spear"][1]:
        while enemy_health > 0:
            print(random.choice(catchphrases))
            enemy_health -= weapon_dict["Spear"][0]
        print("Enemy defeated with the spear!")
    else:
        print("The enemy is too far for a spear attack.")
        missed_shots += 1
        player_health = take_damage(player_health, missed_shots)
    return player_health, missed_shots

weapon_final_choice = int(input("What weapon are you using? For every time you miss a shot, you lose health. (0 for sword, 1 for bow and arrow, 2 for spear): "))

enemy_distance = random.randint(1, 40)
enemy_health = 50
missed_shots = 0

if weapon_final_choice == 0:
    health, missed_shots = sword_combat(enemy_distance, enemy_health, health, missed_shots)
elif weapon_final_choice == 1:
    health, missed_shots = bow_arrow_combat(enemy_distance, enemy_health, health, missed_shots)
elif weapon_final_choice == 2:
    health, missed_shots = spear_combat(enemy_distance, enemy_health, health, missed_shots)

if health <= 0:
    print("Oh no, your health is too low, you perished with the Mongols!")
    sys.exit()
else:
    print("Great job, you completed your first fight! You increased your expierence!")
    experience += 10
    print(experience, " points!")
    pass

print("     _____")
print("    /     \\")
print("   /       \\")
print("  |   /\\_/\\ |")
print("  |  ( O O )|")
print("  |   \\_v_/ |")
print("   \\_______/")
print("     |   |")
print("     |   |")
print("   __|   |__")
print("  /  |   |  \\")
print(" /   |   |   \\")
print("|    |   |    |")
print("     |   |")
print("    /     \\")
print("   /       \\")
print("  /__     __\\")
print("     |___|")



        






Hello explored traveler!
My name is Ivan I, prince of the Rus, in 13th century. These lands have been torn down and broken apart by the Mongols, please, do something!
As you help prevent and defend attacks from the Mongols, your stats change: health:  100 , experience:  0
Now it's time to choose your main weapon!
Good choice, a sword is used in closer combat. The damage it can deal is  25 , and its attack distance is 10
Good choice, a bow and arrow is used in longer range combat. The damage it can deal is  20 , and its attack distance is 40
Good choice, a spear is used in very close combat. The damage it can deal is  50 , and its attack distance is 5
10 years later ....
OH NO, GENGHIS KHAN IS ATTACKING!
DEPLOY ALL FORCES
Bam!
Smack!
Strike!
Enemy defeated with the bow and arrow!
Great job, you completed your first fight! You increased your expierence!
10  points!
     _____
    /     \
   /       \
  |   /\_/\ |
  |  ( O O )|
  |   \_v_/ |
   \_______/
     |   |
     |   |
   __|   |__
  /  |   |  \
 /   |   |   \
|    |   |    |
     |   |
    /     \
   /       \
  /__     __\
     |___|