Alara’s Code with a List and Iteration


# Program Function and Purpose
## Program With a List

# Importing necessary libraries (optional for this example)
import random

# Step 1: Create a list of numbers
numbers = [random.randint(1, 100) for _ in range(10)]

## Step 2: Display the list 
print("List of Numbers:", numbers)

# Step 3: Calculate the sum of the numbers
sum_of_numbers = sum(numbers)
print("Sum of Numbers:", sum_of_numbers)

# Step 4: Find the maximum and minimum numbers in the list
max_number = max(numbers)
min_number = min(numbers)
print("Maximum Number:", max_number)
print("Minimum Number:", min_number)

## This example demonstrates the creation of a program with a list of random numbers and performs basic operations like displaying the list, calculating the sum, and finding the maximum and minimum numbers in the list.

# Program With Iteration

### Step 1: Create a list of numbers
numbers = [1, 2, 3, 4, 5]

squared_numbers = []
for num in numbers:
    squared_numbers.append(num ** 2)

### Step 3: Display the squared numbers
print("Original Numbers:", numbers)
print("Squared Numbers:", squared_numbers)

### Step 4: Calculate the sum of squared numbers using iteration
sum_of_squared_numbers = 0
for num in squared_numbers:
    sum_of_squared_numbers += num

print("Sum of Squared Numbers:", sum_of_squared_numbers)

##In this example, we create a program with iteration using a for loop. We iterate through a list of numbers, square each number, display the squared numbers, and then calculate the sum of squared numbers using iteration. For loops are very useful in JavaScript.



List of Numbers: [59, 67, 18, 31, 25, 37, 59, 61, 100, 10]
Sum of Numbers: 467
Maximum Number: 100
Minimum Number: 10
Original Numbers: [1, 2, 3, 4, 5]
Squared Numbers: [1, 4, 9, 16, 25]
Sum of Squared Numbers: 55

Alisha’s Program with Dictionary

# Program with Dictionary
# Create a dictionary of words and their meanings
dictionary = {
    "apple": "a fruit that grows on trees and is typically red or green",
    "car": "a four-wheeled motor vehicle used for transportation",
    "computer": "an electronic device that processes and stores data",
    "dog": "a domesticated mammal often kept as a pet",
    "python": "a high-level programming language",
    "cat": "a small domesticated carnivorous mammal",
    "book": "a written or printed work consisting of pages glued or sewn together along one side",
    "house": "a building for human habitation",
    "music": "vocal or instrumental sounds (or both) combined in such a way as to produce beauty of form, harmony, and expression of emotion",
    "friend": "a person whom one knows and with whom one has a bond of mutual affection",
    "beach": "a pebbly or sandy shore, especially by the ocean between high- and low-water marks",
    "sun": "the star around which the earth orbits",
    "moon": "the natural satellite of the earth, visible (chiefly at night) by reflected light from the sun",
    "flower": "the seed-bearing part of a plant, consisting of reproductive organs (stamens and carpels) that are typically surrounded by a brightly colored corolla",
    "bicycle": "a vehicle with two wheels that is propelled by pedals and steered with handlebars",
    "ocean": "a very large expanse of sea, in particular, each of the main areas into which the sea is divided geographically",
    "bookstore": "a store where books are sold",
    "school": "an institution for educating children",
    "teacher": "a person who teaches, especially in a school",
    "student": "a person who is studying at a school or college",
    "restaurant": "a place where people pay to sit and eat meals that are cooked and served on the premises",
    "movie": "a story or event recorded by a camera as a set of moving images and shown in a theater or on television; a motion picture",
    "guitar": "a stringed musical instrument with a fretted fingerboard, typically incurved sides, and six or twelve strings",
    "computer science": "the study of computers and computing technologies",
    "football": "a ball used in football, either oval (as in American football) or round (as in soccer), typically made of leather or plastic and filled with compressed air",
    "pizza": "a dish of Italian origin consisting of a flat, round base of dough baked with a topping of tomato sauce and cheese, typically with added meat or vegetables",
    "space": "a continuous area or expanse that is free, available, or unoccupied",
    "universe": "all existing matter, space, and time considered as a whole; the cosmos",
    "tree": "a woody perennial plant, typically having a single stem or trunk growing to a considerable height and bearing lateral branches at some distance from the ground",
    "happiness": "the state of being happy",
    "sadness": "the quality of being sad; sorrow",
    "love": "an intense feeling of deep affection",
    "hate": "feel intense or passionate dislike for someone",
    "freedom": "the power or right to act, speak, or think as one wants without hindrance or restraint",
    "government": "the governing body of a nation, state, or community",
    "oxygen": "a chemical element with the symbol O and atomic number 8",
    "hydrogen": "a colorless, odorless, highly flammable gas",
    "education": "the process of receiving or giving systematic instruction, especially at a school or university",
    "library": "a building or room containing collections of books, periodicals, and sometimes films and recorded music for use or borrowing by the public or the members of an institution",
    "movie theater": "a place where movies are shown to an audience on a big screen",
    "beauty": "a combination of qualities, such as shape, color, or form, that pleases the aesthetic senses, especially the sight",
    "friendship": "the emotions or conduct of friends; the state of being friends",
    "laughter": "the action or sound of laughing",
    "peace": "freedom from disturbance; tranquility",
    "war": "a state of armed conflict between different nations or states or different groups within a nation or state",
    "oceanography": "the branch of science that deals with the physical and biological properties and phenomena of the sea",
    "chemistry": "the branch of science that deals with the identification of the substances of which matter is composed; the investigation of their properties and the ways in which they interact, combine, and change; and the use of these processes to form new substances",
    "biology": "the scientific study of living organisms and their interactions with each other and their environments",
    "history": "the study of past events, particularly in human affairs",
    "geography": "the study of the physical features of the earth and its atmosphere, and of human activity as it affects and is affected by these, including the distribution of populations and resources, land use, and industries",
    "physics": "the branch of science concerned with the nature and properties of matter and energy",
    "astronomy": "the branch of science that deals with celestial objects, space, and the physical universe as a whole",
    "mathematics": "the abstract science of number, quantity, and space, either as abstract concepts (pure mathematics), or as applied to other disciplines such as physics and engineering (applied mathematics)",
    "chemistry": "the branch of science that deals with the identification of the substances of which matter is composed; the investigation of their properties and the ways in which they interact, combine, and change; and the use of these processes to form new substances",
    "biology": "the scientific study of living organisms and their interactions with each other and their environments",
    "history": "the study of past events, particularly in human affairs",
    "geography": "the study of the physical features of the earth and its atmosphere, and of human activity as it affects and is affected by these, including the distribution of populations and resources, land use, and industries",
    "physics": "the branch of science concerned with the nature and properties of matter and energy",
    "astronomy": "the branch of science that deals with celestial objects, space, and the physical universe as a whole",
    "mathematics": "the abstract science of number, quantity, and space, either as abstract concepts (pure mathematics), or as applied to other disciplines such as physics and engineering (applied mathematics)",
    "chemistry": "the branch of science that deals with the identification of the substances of which matter is composed; the investigation of their properties and the ways in which they interact, combine, and change; and the use of these processes to form new substances",
    "biology": "the scientific study of living organisms and their interactions with each other and their environments",
    "history": "the study of past events, particularly in human affairs",
    "geography": "the study of the physical features of the earth and its atmosphere, and of human activity as it affects and is affected by these, including the distribution of populations and resources, land use, and industries",
    "physics": "the branch of science concerned with the nature and properties of matter and energy",
    "astronomy": "the branch of science that deals with celestial objects, space, and the physical universe as a whole",
    "mathematics": "the abstract science of number, quantity, and space, either as abstract concepts (pure mathematics), or as applied to other disciplines such as physics and engineering (applied mathematics)",
    "chemistry": "the branch of science that deals with the identification of the substances of which matter is composed; the investigation of their properties and the ways in which they interact, combine, and change; and the use of these processes to form new substances",
    "biology": "the scientific study of living organisms and their interactions with each other and their environments",
    "history": "the study of past events, particularly in human affairs",
    "geography": "the study of the physical features of the earth and its atmosphere, and of human activity as it affects and is affected by these, including the distribution of populations and resources, land use, and industries",
    "physics": "the branch of science concerned with the nature and properties of matter and energy",
    "astronomy": "the branch of science that deals with celestial objects, space, and the physical universe as a whole",
    "mathematics": "the abstract science of number, quantity, and space, either as abstract concepts (pure mathematics), or as applied to other disciplines such as physics and engineering (applied mathematics)",
}
# Define a function to look up word meanings
def lookup_word(word):
    return dictionary.get(word.lower(), "Sorry, we don't have this word in our dictionary yet!")
# Interactive loop
while True:
    print("\nInteractive Dictionary")
    print("Enter a word to look up its meaning (type 'exit' to quit):")
    user_input = input("> ").lower().strip()  # Convert user input to lowercase for case-insensitive lookup
    if user_input == 'exit':
        print("Thanks for using this, bye!")
        break
    meaning = lookup_word(user_input)
    print(f"Meaning: {meaning}")

Alisha’s Program with Statistical Calculation

def add(x, y):
    return x + y
def subtract(x, y):
    return x - y
def multiply(x, y):
    return x * y
def divide(x, y):
    if y == 0:
        return Cannot divide by zero
    return x / y
def calculate_average(numbers):
    if not numbers:
        return No numbers provided
    total = sum(numbers)
    return total / len(numbers)
while True:
    print(Options:)
    print(Enter add for addition)
    print(Enter subtract for subtraction)
    print(Enter multiply for multiplication)
    print(Enter divide for division)
    print(Enter average for average calculation)
    print(Enter quit to end the program)
    user_input = input(: )
    if user_input == quit:
        break
    elif user_input in [add, subtract, multiply, divide]:
        num1 = float(input(Enter first number: ))
        num2 = float(input(Enter second number: ))
        if user_input == add:
            print(Result:, add(num1, num2))
        elif user_input == subtract:
            print(Result:, subtract(num1, num2))
        elif user_input == multiply:
            print(Result:, multiply(num1, num2))
        elif user_input == divide:
            print(Result:, divide(num1, num2))
    elif user_input == average:
        num_list = input(Enter a list of numbers separated by spaces: ).split()
        num_list = [float(num) for num in num_list]
        print(Average:, calculate_average(num_list))
    else:
        print(Invalid input. Please try again.)

Tara’s Program with Condition and Selection

# Enter the number of voters
voters = (input("Enter the number of voters"))
try:
    # Convert input string to integer
    numVoters = int(voters)
    # List of political parties
    mylist = ["Democrat", "Republican", "Independent"]
    # Randoml select a political party using weights for 1000 voters
    result = random.choices(mylist, weights = [980,940,1000], k = numVoters)
    # count the results by political party and add to a dictionary
    res = Counter(result)
    print(res)
    # Analyze the results by comparing the number of votes for each political party to  determine which party won and the difference in the number of votes
    if res["Democrat"] > res["Republican"] and res["Democrat"] > res["Independent"]:
        diffRep = res["Democrat"] - res["Republican"]
        diffInd = res["Democrat"] - res["Independent"]
        print(f"Democrats won by {diffRep} votes, relative to Republican" )
        print(f"Democrats won by {diffInd} votes, relative to Independent" )
    elif res["Republican"] > res["Democrat"] and res["Republican"] > res["Independent"]:
        diffDem = res["Republican"] - res["Democrat"]
        diffInd = res["Republican"] - res["Independent"]
        print(f"Republican won by {diffDem} votes, relative to Democrat" )
        print(f"Republican won by {diffInd} votes, relative to Independent" )
    elif res["Independent"] > res["Democrat"] and res["Independent"] > res["Republican"]:
        diffRep = res["Independent"] - res["Republican"]
        diffDem = res["Independent"] - res["Democrat"]
        print(f"Independent won by {diffRep} votes, relative to Republican" )
        print(f"Independent won by {diffDem} votes, relative to Democrat" )
    else:
        print("No one won")
except ValueError:
    print("Please enter an integer")

Sharon’s Program with