Skip to the content.

3.3 and 3.5 Homework and Popcorn hacks

3.3

Popcorn Hacks

Hack #1

import sys  # for stopping the program

def checksIfLessThanZero():
    while True:
        try:
            number = input("Give me a number or say STOP to stop: ")
            if number == "STOP":
                sys.exit("Stopping")
            number = int(number)  # Only convert to int if it's not STOP
        except ValueError:  # Catch specific errors related to invalid input
            print("You didn't put in a number you silly goose")
            continue
        else:
            break

    if number < 0:
        print("That number is less than zero")
    else:
        print("That number is greater than or equal to zero")

while True:
    checksIfLessThanZero()
That number is greater than or equal to zero
That number is less than zero
You didn't put in a number you silly goose



An exception has occurred, use %tb to see the full traceback.


SystemExit: Stopping

Hack #2

import sys # For exiting the program


def checkScores():


    while True:


        score1 = input("Enter the first score or say STOP to end the program: ")


        if (score1 == "STOP"): sys.exit("Stopping")

        score2 = input("Enter the second score: ")

        try:
            score1 = float(score1)
            score2 = float(score2)

        except: print("you're a silly goose, enter a real number")

        else: break

    if score1 >= 70 and score2 >= 70: print("The student passed both subjects.")

    elif score1 >= 70: print("The student only passed the first class")

    elif score2 >= 70: print("The student only passed the second class")

    else: print("The student is a silly goose and did not pass either classes")


    
while True:
    checkScores()
The student passed both subjects.
The student only passed the second class
The student only passed the first class
The student is a silly goose and did not pass either classes
you're a silly goose, enter a real number



An exception has occurred, use %tb to see the full traceback.


SystemExit: Stopping

Hack #3

import sys

VOWELS = "aeiou"

while True:

    ifVowels = False

    userInput = input("Please enter a string or say STOP to end the program: ")
    if (userInput == "STOP"): sys.exit("stopping")

    for char in userInput:
        if (char.lower() in VOWELS): 
            print("There are vowels")
            ifVowels = True
            break

    if (not ifVowels): print("there are no vowels")
There are vowels
There are vowels
There are vowels
there are no vowels
there are no vowels
there are no vowels
There are vowels



An exception has occurred, use %tb to see the full traceback.


SystemExit: stopping

Homework Hacks

Hack #1

import itertools

# Define headers for the truth table
headers = ['A', 'B', 'A AND B', 'NOT (A AND B)', 'NOT A OR NOT B', 'A OR B', 'NOT (A OR B)', 'NOT A AND NOT B']

# Generate all possible truth values for A and B (True/False)
values = list(itertools.product([True, False], repeat=2))

def print_truth_table():
    # Print the header row
    print(f"{' | '.join(headers)}")
    print("-" * 80)

    # Iterate over all combinations of truth values
    for A, B in values:
        # Calculate the values for each column based on A and B
        a_and_b = A and B
        not_a_and_b = not (A and B)
        not_a_or_not_b = not A or not B  # De Morgan's Law equivalent to NOT (A AND B)
        a_or_b = A or B
        not_a_or_b = not (A or B)
        not_a_and_not_b = not A and not B  # De Morgan's Law equivalent to NOT (A OR B)1

        # Print each row of the truth table
        print(f"{A:<5} | {B:<5} | {a_and_b:<9} | {not_a_and_b:<12} | {not_a_or_not_b:<13} | {a_or_b:<7} | {not_a_or_b:<12} | {not_a_and_not_b:<13}")

# Generate and print the truth table
print_truth_table()

Hack #2

def de_morgans_game():
    print("Welcome to the Yes or No Game (based on De Morgan's Law)!")
    print("Answer 'yes' or 'no' to the following questions:")

    # Get user inputs
    sunny = input("Is it sunny today (yes/no)? ").strip().lower() == 'yes'
    raining = input("Is it raining today (yes/no)? ").strip().lower() == 'yes'

    # De Morgan's Law: !(A and B) == !A or !B
    if not (sunny and raining):
        print("It's not both sunny and raining at the same time.")
    else:
        print("Somehow, it's both sunny and raining!")

    # De Morgan's Law: !(A or B) == !A and !B
    if not (sunny or raining):
        print("It's neither sunny nor raining!")
    else:
        print("It's either sunny or raining.")

# Start the game
de_morgans_game()

3.5

Popcorn Hacks

Hack #1

import sys # for exiting the program

# Hack 1: Infinite loop asking for valid list of integers
def sum_of_integers():

    while True:  # Infinite loop


        try:
            user_input = input("Enter a list of integers separated by spaces or say STOP to stop the program: ")

            if (user_input == "STOP"):
                sys.exit("Stopping")

            integers = [int(i) for i in user_input.split()]  # Convert input to list of integers
            total_sum = sum(integers)  # Compute sum
            print(f"The sum of the integers is: {total_sum}")
            
            break  # Exit loop on valid input


        except ValueError:
            print("You're a silly goose! Please enter valid integers.")

while True: # run code indefinetely
    sum_of_integers()

Hack #2

import sys # for exiting the program

# Hack 2: Infinite loop asking for valid popcorn price and number of bags
def popcorn_cost():
    while True:  # Infinite loop for price


        try:
            price_per_bag = input("Enter the price per bag of popcorn or say STOP to end the program: $")
            if (price_per_bag == "STOP"):
                sys.exit("stopping") # ending the program

            price_per_bag = float(price_per_bag)

            break  # Exit loop on valid input


        except ValueError:
            print("You're a silly goose! Please enter a valid number for price.")


    while True:  # Infinite loop for number of bags


        try:
            num_bags = int(input("Enter the number of bags you want to buy: "))
            break  # Exit loop on valid input


        except ValueError:
            print("You're a silly goose! Please enter a valid integer for number of bags.")


    total_cost = price_per_bag * num_bags  # Calculate total cost
    print(f"The total cost for {num_bags} bags is: ${total_cost:.2f}")




# Call the function for indefenitetly
while True:
    popcorn_cost()

Hack #3

import sys # for exiting the program

# Hack 3: Infinite loop asking for valid integer n
def sum_to_n():


    while True:  # Infinite loop for valid input


        try:
            n = input("Enter a positive integer n or say STOP to end the program: ")
            
            if (n == "STOP"):
                sys.exit("stopping")

            n = int(n)

            if n <= 0:
                print("You're a silly goose! Please enter a positive integer.")
                continue

            total_sum = sum(range(1, n + 1))  # Sum using range
            print(f"The sum of numbers from 1 to {n} is: {total_sum}")

            break  # Exit loop on valid input


        except ValueError:
            print("You're a silly goose! Please enter a valid integer.")

# Call the function indefinetly
while True:
    sum_to_n()

Homework Hacks

Hack #1

import statistics
import sys

# Homework Hack 1: Infinite loop asking for valid list of integers
def mean_and_median():


    while True:  # Infinite loop
        user_input = input("Enter a list of integers separated by spaces (or say STOP to end the program): ")


        if (user_input == "STOP"):  # Check if user wants to stop
            sys.exit("stopping")


        try:
            numbers = [int(i) for i in user_input.split()]  # Convert input to list of integers
            mean_value = statistics.mean(numbers)
            median_value = statistics.median(numbers)
            print(f"Mean: {mean_value}, Median: {median_value}")
            break  # Exit loop on valid input


        except ValueError:
            print("You're a silly goose! Please enter valid integers.")

# Call the function indefinetly
while True:
    mean_and_median()

Hack #2

import sys

# Homework Hack 2: Infinite loop asking for valid integer input
def collatz_sequence():
    
    while True:  # Infinite loop

        user_input = input("Enter a positive integer for Collatz sequence (or say STOP to end the program): ")


        if user_input.upper() == "STOP":  # Check if user wants to stop
            sys.exit("stopping")


        try:
            a = int(user_input)  # Convert input to integer

            if a <= 0:
                print("You're a silly goose! Please enter a positive integer.")
                continue

            sequence = [a]

            while a != 1:

                if a % 2 == 0:
                    a //= 2

                else:
                    a = 3 * a + 1

                sequence.append(a)

            print(f"Collatz sequence: {sequence}")
            break  # Exit loop on valid input


        except ValueError:
            print("You're a silly goose! Please enter a valid integer.")


# Call the function indefenitely
while True:
    collatz_sequence()