Skip to the content.

problems

Quick launch into Variables, Functions, Arrays, Classes, Objects.

JavaScript

3.2 Homework Hacks

3.2.1 Popcorn Hack 1

Create a simple python script to add two integers.

# Define a function that takes two integers as inputs
def add_two_integers(a, b):
    # Return the sum of the two integers
    return a + b

# Prompt the user to enter the first integer and convert the input to an integer
num1 = int(input("Enter first integer: "))

# Prompt the user to enter the second integer and convert the input to an integer
num2 = int(input("Enter second integer: "))

# Call the function with the two integers provided by the user and store the result in 'result'
result = add_two_integers(num1, num2)

# Print out the result in a formatted string
print(f"The sum of {num1} and {num2} is: {result}")

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

ValueError                                Traceback (most recent call last)

Cell In[1], line 7
      4     return a + b
      6 # Prompt the user to enter the first integer and convert the input to an integer
----> 7 num1 = int(input("Enter first integer: "))
      9 # Prompt the user to enter the second integer and convert the input to an integer
     10 num2 = int(input("Enter second integer: "))


ValueError: invalid literal for int() with base 10: ''

3.2.1 Popcorn Hack 2

Popcorn Hack: Simple Python script to count the length of a string.

# Prompt the user to enter a string and store the input in the variable 'user_string'
user_string = input("Enter a string: ")

# Use the len() function to get the length of the string and store it in 'string_length'
string_length = len(user_string)

# Print the length of the string in a formatted message
print(f"The length of the string is: {string_length}")

3.2.1 Popcorn Hack 3

Popcorn Hack: Simple JavaScript function to check for null(none in python).

// Define a function that takes one argument
function isNull(value) {
    // Check if the value is strictly equal to null
    return value === null;
}

// Example usage
let value = null; // You can change this to test other values
console.log(isNull(value)); // Prints 'true' if value is null, otherwise 'false'

3.2.2 Popcorn Hack

Create a dictionary, update an item, and add an item.

# Creating a dictionary with initial details about a person
person = {
    "name": "Aranya",      # Name of the person
    "age": 17,            # Age of the person
    "is_student": False   # Boolean indicating if the person is a student
}

# Updating the "age" item
person["age"] = 68  # Modify the age from 25 to 26

# Adding a new item to the dictionary
person["friend"] = {        # Adding a new key "friend" with a nested dictionary as the value
    "name": "Jonah",        # Name of the friend
    "age": 15,              # Age of the friend
    "is_student": True      # Boolean indicating if the friend is a student
}

# Printing the updated dictionary to see all changes
print(person)  # Output the updated dictionary to the console

3.2.3 Popcorn Hack

Use JSON to make a dictionary, modify it, and update the changes.

import json

# Step 1: Creating a dictionary in JSON format and saving it to a file
# Initial dictionary
person = {
    "name": "Alice",
    "age": 25,
    "is_student": False
}

# Write the dictionary to a JSON file
with open('person.json', 'w') as json_file:
    json.dump(person, json_file, indent=4)  # Save dictionary to JSON file with readable formatting

# Step 2: Loading the dictionary from the JSON file
with open('person.json', 'r') as json_file:
    person = json.load(json_file)  # Load the JSON file back into a dictionary

# Step 3: Modifying the dictionary
person["age"] = 26                 # Update the age
person["friend"] = {               # Add a new nested dictionary for a friend
    "name": "David",
    "age": 22,
    "is_student": True
}

# Step 4: Updating the JSON file with the modified dictionary
with open('person.json', 'w') as json_file:
    json.dump(person, json_file, indent=4)  # Save the updated dictionary back to the JSON file

3.2.3 Homework Problem 1


1. Create a dictionary with at least 3 keys. Print the dictionary.
2. Start with this dictionary: person = {“name”: “Alice”, “age”: 30}
i. Update the age to 31
ii. print the updated dictionary.

# Task 1: Create a dictionary with at least 3 keys and print the dictionary

# Creating a dictionary with 3 key-value pairs
car = {
    "make": "Toyota",       # Car manufacturer
    "model": "Camry",       # Model of the car
    "year": 2020            # Year of manufacture
}

# Printing the dictionary to the console
print("Initial car dictionary:", car)  # Outputs the dictionary with its keys and values


# Task 2: Start with a given dictionary, update a key, and print the updated dictionary

# Initializing the dictionary with the given details
person = {
    "name": "Alice",  # Name of the person
    "age": 30         # Age of the person
}

# Updating the "age" key to a new value
person["age"] = 31  # Changes the age from 30 to 31

# Printing the updated dictionary to show the change
print("Updated person dictionary:", person)  # Outputs the dictionary with the updated age