import sys
from typing import Union

# Define types for mean function, trying to analyze input possibilities
Number = Union[int, float]  # Number can be either int or float type
Numbers = list[Number] # Numbers is a list of Number types
Scores = Union[Number, Numbers] # Scores can be single or multiple 

def mean(scores: Scores, method: int = 1) -> float:
    """
    Calculate the mean of a list of scores.
    
    Average and Average2 are hidden functions performing mean algorithm

    If a single score is provided in scores, it is returned as the mean.
    If a list of scores is provided, the average is calculated and returned.
    """
    
    def average(scores): 
        """Calculate the average of a list of scores using a Python for loop with rounding."""
        sum = 0
        len = 0
        for score in scores:
            if isinstance(score, Number):
                sum += score
                len += 1
            else:
                print("Bad data: " + str(score) + " in " + str(scores))
                sys.exit()
        return sum / len
    
    def average2(scores):
        """Calculate the average of a list of scores using the built-in sum() function with rounding."""
        return sum(scores) / len(scores)

    # test to see if scores is  a list of numbers
    if isinstance(scores, list):
        if method == 1:  
            # long method
            result = average(scores)
        else:
            # built in method
            result = average2(scores)
        return round(result + 0.005, 2)
    
    return scores # case where scores is a single valu

# try with one number
singleScore = 100
print("Print test data: " + str(singleScore))  # concat data for single line
print("Mean of single number: " + str(mean(singleScore)))

print()

# define a list of numbers
testScores = [90.5, 100, 85.4, 88]
print("Print test data: " + str(testScores))
print("Average score, loop method: " + str(mean(testScores)))
print("Average score, function method: " +  str(mean(testScores, 2)))

print()

badData = [100, "NaN", 90]
print("Print test data: " + str(badData))
print("Mean with bad data: " + str(mean(badData)))
Print test data: 100
Mean of single number: 100

Print test data: [90.5, 100, 85.4, 88]
Average score, loop method: 90.98
Average score, function method: 90.98

Print test data: [100, 'NaN', 90]
Bad data: NaN in [100, 'NaN', 90]



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


SystemExit



/usr/lib/python3/dist-packages/IPython/core/interactiveshell.py:3465: UserWarning: To exit: use 'exit', 'quit', or Ctrl-D.
  warn("To exit: use 'exit', 'quit', or Ctrl-D.", stacklevel=1)
# median
import sys
from typing import Union

# Define types for mean function, trying to analyze input possibilities
Number = Union[int, float]  # Number can be either int or float type
Numbers = list[Number] # Numbers is a list of Number types
Scores = Union[Number, Numbers] # Scores can be single or multiple

def find_median(numbers):
    # Sort the list in order of smallest to largest
    numbers.sort()
    
    # Check if number of elements is even or odd
    num_elements = len(numbers)
    
    if num_elements % 2 == 1:
        # takes the number of elements, divides by 2, and if it is odd, finds the middle number
        median = numbers[num_elements // 2]
    else:
        # If it's not odd, it takes the two closest to the middle and averages
        middle1 = numbers[num_elements // 2 - 1]
        middle2 = numbers[num_elements // 2]
        median = (middle1 + middle2) / 2.0

    return median

# Create an empty list to store the numbers
numbers = []

# Keeps asking for numbers until user types in a non-numeric value
while True:
    try:
        num = float(input("Enter a number (or a non-numeric value to stop): "))
        numbers.append(num)
        # asks for user input w/ input, then converts to string. 
        # From there, the string is converted to a number using float. 
        # Append adds a number to the list as the user types in numbers.
    except ValueError:
        # Can't be converted to a float
        break
    
# Check if there are numbers to calculate the median
if numbers:
    median = find_median(numbers)
    print("Median:", median)
else:
    print("No numbers entered.")
Enter a number (or a non-numeric value to stop): 0
Enter a number (or a non-numeric value to stop): 1
Enter a number (or a non-numeric value to stop): 2
Enter a number (or a non-numeric value to stop): 5
Enter a number (or a non-numeric value to stop): 6
Enter a number (or a non-numeric value to stop): 9
Enter a number (or a non-numeric value to stop): 8
Enter a number (or a non-numeric value to stop): 4
Enter a number (or a non-numeric value to stop): 6
Enter a number (or a non-numeric value to stop): 
Median: 5.0
# Standard Deviation

import math

# Function to calculate the mean (average) of a list of numbers
def calculate_mean(numbers):
    return sum(numbers) / len(numbers)

# Function to calculate the standard deviation
def calculate_standard_deviation(numbers):
    mean = calculate_mean(numbers)
    squared_deviations = [(x - mean) ** 2 for x in numbers]
    variance = sum(squared_deviations) / len(numbers)
    std_deviation = math.sqrt(variance)
    return std_deviation

# Create an empty list to store the numbers
numbers = []

# Prompt the user for input until they enter a non-numeric value
while True:
    try:
        num = float(input("Enter a number (or a non-numeric value to stop): "))
        numbers.append(num)
    except ValueError:
        break

# Check if there are numbers to calculate the standard deviation
if numbers:
    std_deviation = calculate_standard_deviation(numbers)
    print("Standard Deviation:", std_deviation)
else:
    print("No numbers entered.")
Standard Deviation: 1.479019945774904