0% found this document useful (0 votes)
7 views16 pages

Python Statistical Calculator Code

This document describes a simple statistical calculator implemented in Python, HTML, CSS, and JavaScript. The calculator allows users to compute mean, median, mode, and standard deviation of a list of numbers entered by the user. It includes a user-friendly interface and detailed explanations of the code structure and functionality.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views16 pages

Python Statistical Calculator Code

This document describes a simple statistical calculator implemented in Python, HTML, CSS, and JavaScript. The calculator allows users to compute mean, median, mode, and standard deviation of a list of numbers entered by the user. It includes a user-friendly interface and detailed explanations of the code structure and functionality.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Overview

This code is a simple statistical calculator that performs basic statistical operations:
calculating the mean, median, mode, and standard deviation of a set of numbers
provided by the user.

Code
import statistics

def print_menu():

print("Statistical Calculator")

print("1. Calculate Mean")

print("2. Calculate Median")

print("3. Calculate Mode")

print("4. Calculate Standard Deviation")

print("5. Exit")

def get_data():

data = input("Enter the data separated by commas: ")

data = list(map(float, [Link](',')))

return data

def calculate_mean(data):

return sum(data) / len(data)

def calculate_median(data):

[Link]()

mid = len(data) // 2
if len(data) % 2 == 0:

return (data[mid - 1] + data[mid]) / 2

else:

return data[mid]

def calculate_mode(data):

return [Link](data)

def calculate_std_dev(data):

return [Link](data)

def main():

while True:

print_menu()

choice = int(input("Enter your choice: "))

if choice == 1:

data = get_data()

print(f"Mean: {calculate_mean(data)}")

elif choice == 2:

data = get_data()

print(f"Median: {calculate_median(data)}")

elif choice == 3:

data = get_data()

print(f"Mode: {calculate_mode(data)}")

elif choice == 4:

data = get_data()

print(f"Standard Deviation: {calculate_std_dev(data)}")


elif choice == 5:

break

else:

print("Invalid choice. Please try again.")

if __name__ == "__main__":

main()

Breakdown of the Code


1. Imports:

The statistics module is imported to utilize its built-in functions for


o
calculating mode and standard deviation.
2. Functions:

o print_menu(): Displays the menu options for the user, allowing them to
select a statistical operation or exit the program.
o get_data(): Prompts the user to enter a list of numbers separated by
commas, which are then converted to a list of floats for calculations.
o calculate_mean(data): Computes the mean (average) of the given list of
numbers by summing them up and dividing by the count of numbers.
o calculate_median(data): Determines the median (middle value) of the list.
It first sorts the data, then checks if the count is even or odd to return the
appropriate median value.
o calculate_mode(data): Uses the [Link]() function to find and
return the mode (most common value) of the data.
o calculate_std_dev(data): Uses the [Link]() function to
calculate and return the standard deviation of the data.

This code implements a simple statistical calculator in Python. The calculator allows
users to perform basic statistical operations on a list of numeric data entered by the
user. Here’s a breakdown of its components:

3. Imports:

o import statistics: This imports the statistics module, which provides


functions for statistical calculations.
4. Function print_menu:
o Displays a menu of options for the user to choose from, including
calculating the mean, median, mode, standard deviation, or exiting the
program.
5. Function get_data:
o Prompts the user to input data in a comma-separated format (e.g., "1, 2,
3").
o Converts this input into a list of floats and returns it.
6. Function calculate_mean(data):
o Takes a list of numerical data as input and returns the mean (average) by
summing all values and dividing by the number of values.
7. Function calculate_median(data):
o Sorts the data list and finds the median:
 If the number of data points is odd, it returns the middle value.
 If even, it calculates the median as the average of the two middle
values.
8. Function calculate_mode(data):
o Uses the [Link] function to return the mode (the most common
value) of the data list.
9. Function calculate_std_dev(data):
o Uses the [Link] function to calculate and return the standard
deviation, measuring data spread.
10. Function main:
o The core of the program, which runs in a loop:
 It repeatedly displays the menu and prompts the user for a choice.
 Depending on the user’s choice, it calls the appropriate function to
calculate the required statistic after obtaining the data.
 If the user selects '5', the program exits.
 If the user enters an invalid choice, it prompts them to try again.

11. Execution:

o If the script is run directly (as opposed to being imported), it calls


the main() function to start the program.
12.

13. Main Program Loop:

o The main() function contains a while True loop that continuously displays
the menu and prompts the user for a choice.
o Based on the user's input, it:
 Calls the relevant function to perform the requested calculation.
 Displays the result of the calculation.
 Exits the loop and program if the user chooses option 5, or provides
an error message for invalid choices.

14. Execution Point:

o The line if __name__ == "__main__": main() ensures that


the main() function is called when the script is executed directly.

How to Use It
To use this calculator:

 Run the script.


 Choose a statistical operation by entering the corresponding number.
 Input a list of numbers when prompted.
 View the result displayed on the screen.

How the Calculator Works:

1. Menu Display: The print_menu function shows a simple menu with options to calculate
Mean, Median, Mode, Standard Deviation, or Exit.
2. Data Entry: The get_data function takes a comma-separated string of numbers from
the user, converts it into a list of floats.
3. Calculations:
o Mean: Calculated by dividing the sum of data by the number of data points.
o Median: The middle value of the sorted data. If there are an even number of data
points, it averages the two middle numbers.
o Mode: The most frequently occurring value in the data.
o Standard Deviation: Measures the amount of variation or dispersion in a set of
values.
4. Loop for Choices: The main function loops, allowing the user to choose different
statistical measures to calculate or exit.

Summary
In summary, this code provides a user-friendly interface for calculating basic statistical
measures, efficiently handling input and results while leveraging Python's capabilities
for statistical computations.
MINE
Step 1: HTML Structure

Create a file named [Link]:

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<meta name="viewport" content="width=device-width, initial-scale=1.0">

<title>Statistical Calculator</title>

<link rel="stylesheet" href="[Link]">

</head>

<body>

<div class="calculator">

<div class="display">

<input type="text" id="data-input" placeholder="Enter data separated by commas">

</div>

<div class="buttons">

<button onclick="calculateMean()">Mean</button>

<button onclick="calculateMedian()">Median</button>

<button onclick="calculateMode()">Mode</button>

<button onclick="calculateStdDev()">Std Dev</button>

<button onclick="clearDisplay()">Clear</button>

</div>

<div class="result" id="result"></div>

</div>

<script src="[Link]"></script>
</body>

</html>

DESCRIPTION:

This code is an HTML document that creates a simple statistical calculator web
application. Here's a breakdown of its components:

1. DOCTYPE and HTML Structure:

o The document starts with <!DOCTYPE html>, indicating that it's an HTML5
document.
o The <html> tag specifies the language as English ( lang="en").

2. Head Section:

o <meta charset="UTF-8">: Sets the character encoding to UTF-8, which


supports a wide range of characters.
o <meta name="viewport" content="width=device-width, initial-
scale=1.0">: Ensures that the web page is responsive and looks good on
various devices by controlling the layout on mobile browsers.
o <title>Statistical Calculator</title>: Defines the title of the web page
that appears in the browser tab.
o <link rel="stylesheet" href="[Link]">: Links to an external CSS file
([Link]) for styling the calculator.

3. Body Section:

o The <body> tag contains the content of the web page.


o <div class="calculator">: A container for the entire calculator
component.
o <div class="display">: Contains an input field where users can enter data
(numbers separated by commas).
 <input type="text" id="data-input" placeholder="Enter data
separated by commas">: An input box with a placeholder for user
guidance.
o <div class="buttons">: This section holds the calculator buttons for
various statistical computations.
 Each <button> element calls a corresponding JavaScript function
(like calculateMean(), calculateMedian(), etc.) when clicked.
o <div class="result" id="result"></div>: This empty div is where the
results of the calculations will be displayed.

4. Script Section:

o <script src="[Link]"></script>: Links to an external JavaScript file


([Link]), which contains the functions to perform the calculations
triggered by button clicks.
In summary, this HTML document sets up a user interface for a statistical calculator that
performs calculations such as mean, median, mode, and standard deviation, while also
providing functionality to clear the input and display results dynamically.

Step 2: CSS Styling

Create a file named [Link]:

body {

font-family: Arial, sans-serif;

background-color: #f0f0f0;

display: flex;

justify-content: center;

align-items: center;

height: 100vh;

margin: 0;

.calculator {

background-color: #fff;

padding: 20px;

border-radius: 8px;

box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);

width: 300px;

text-align: center;

.display {

margin-bottom: 20px;

}
.display input {

width: 100%;

padding: 10px;

font-size: 16px;

border-radius: 4px;

border: 1px solid #ccc;

.buttons {

margin-bottom: 20px;

.buttons button {

width: 100px;

padding: 10px;

font-size: 16px;

margin: 5px;

border: none;

border-radius: 4px;

background-color: #007bff;

color: #fff;

cursor: pointer;

.buttons button:hover {

background-color: #0056b3;

}
.result {

font-size: 18px;

font-weight: bold;

DESCRIPTION:

This code is a CSS stylesheet used for styling a simple calculator web
application. Here's a clear and concise explanation of the styles defined in
the code:

1. Body Styling:

o font-family: Arial, sans-serif;: Sets the font to Arial or a sans-


serif fallback.
o background-color: #f0f0f0;:Applies a light gray background color
to the entire page.
o display: flex;: Uses Flexbox layout to create a flexible layout.
o justify-content: center;: Centers the calculator horizontally.
o align-items: center;: Centers the calculator vertically within the
viewport.
o height: 100vh;: Sets the height of the body to the full height of the
viewport.
o margin: 0;: Removes any default margin around the body.

2. Calculator Styling:

o .calculator: This class is for the main calculator container.


o background-color: #fff;: Sets the background color to white.
o padding: 20px;: Adds padding inside the calculator for spacing.
o border-radius: 8px;: Rounds the corners of the calculator.
o box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);: Adds a subtle shadow for
a 3D effect.
o width: 300px;: Sets the width of the calculator to 300 pixels.
o text-align: center;: Centers the text inside the calculator.

3. Display Area:

o .display:This class targets the display area at the top of the


calculator.
o margin-bottom: 20px;: Adds space below the display area.
4. Display Input:

o .display input: Styles the input field inside the display.


o width: 100%;: Makes the input field expand to the full width of the
calculator.
o padding: 10px;: Adds padding inside the input field for comfort.
o font-size: 16px;: Sets the font size for the text inside the input.
o border-radius: 4px;: Rounds the corners of the input field.
o border: 1px solid #ccc;: Applies a light gray border around the
input.

5. Button Container:

o .buttons: This class targets the area containing the buttons.


o margin-bottom: 20px;: Adds space below the button container.

6. Button Styling:

o .buttons button: Styles the buttons within the button container.


o width: 100px;: Sets a fixed width of 100 pixels for buttons.
o padding: 10px;: Adds padding inside buttons.
o font-size: 16px;: Sets the font size for button text.
o margin: 5px;: Adds space around buttons.
o border: none;: Removes the default border.
o border-radius: 4px;: Rounds the corners of buttons.
o background-color: #007bff;: Applies a blue background color to
buttons.
o color: #fff;: Sets the text color to white.
o cursor: pointer;: Changes the mouse cursor to a pointer when
hovering over buttons.

7. Button Hover Effect:

o .buttons button:hover: Changes the background color of buttons


when hovered.
o background-color: #0056b3;: Specifies a darker blue background for
the hover state.

8. Result Display:

o .result: This class styles the area where results are displayed.
o font-size: 18px;: Increases the font size for better visibility.
o font-weight: bold;: Makes the text bold for emphasis.

Overall, this CSS code creates a visually appealing and user-friendly


calculator interface with a modern design.
Step 3: JavaScript Logic

Create a file named [Link]:

function getData() {

const input = [Link]("data-input").value;

const data = [Link](',').map(Number);

return data;

function calculateMean() {

const data = getData();

if ([Link] > 0) {

const mean = [Link]((acc, val) => acc + val, 0) / [Link];

displayResult(`Mean: ${mean}`);

} else {

displayResult('Please enter valid data.');

function calculateMedian() {

const data = getData();

if ([Link] > 0) {

[Link]((a, b) => a - b);

const mid = [Link]([Link] / 2);

const median = [Link] % 2 === 0 ? (data[mid - 1] + data[mid]) / 2 : data[mid];

displayResult(`Median: ${median}`);

} else {

displayResult('Please enter valid data.');


}

function calculateMode() {

const data = getData();

if ([Link] > 0) {

const frequency = {};

[Link](num => frequency[num] = (frequency[num] || 0) + 1);

const maxFreq = [Link](...[Link](frequency));

const mode = [Link](frequency).filter(key => frequency[key] === maxFreq);

displayResult(`Mode: ${[Link](', ')}`);

} else {

displayResult('Please enter valid data.');

function calculateStdDev() {

const data = getData();

if ([Link] > 0) {

const mean = [Link]((acc, val) => acc + val, 0) / [Link];

const variance = [Link]((acc, val) => acc + [Link](val - mean, 2), 0) / [Link];

const stdDev = [Link](variance);

displayResult(`Standard Deviation: ${stdDev}`);

} else {

displayResult('Please enter valid data.');

function clearDisplay() {
[Link]("data-input").value = "";

[Link]("result").innerText = "";

function displayResult(result) {

[Link]("result").innerText = result;

DESCRIPTION:

This code is a JavaScript implementation of simple statistical calculations that can be


performed on user-inputted data. Let's break down the main components:

Main Functions:
1. getData():

o Retrieves the value from an input field with the ID "data-input".


o Splits the input string by commas, converts the split strings to numbers,
and returns an array of these numbers.

2. calculateMean():

o Calls getData() to obtain an array of numbers.


o Checks if the array is not empty; if so, it calculates the mean (average) of
the numbers by adding them up and dividing by the count.
o Displays the result or prompts the user to enter valid data if the array is
empty.

3. calculateMedian():

o Retrieves data similarly using getData().


o Sorts the array of numbers in ascending order.
o Determines the median based on whether the array length is odd or even,
then displays the result.

4. calculateMode():

o Gathers the data from getData().


o Constructs a frequency object to count occurrences of each number.
o Identifies the number(s) with the highest frequency (mode) and displays
the result.
5. calculateStdDev():

o Similar to the previous functions, it fetches the data set.


o Computes the mean, followed by calculating the variance (average of
squared differences from the mean).
o Finally, it calculates the standard deviation by taking the square root of
the variance and displays the result.

Additional Functions:
 clearDisplay():

o Clears the input field and any displayed result.


 displayResult(result):

o Updates an HTML element with the ID "result" to show the computed


statistic or message to the user.

Summary:
This script allows users to input a series of numbers separated by commas and then
calculate statistical metrics such as mean, median, mode, and standard deviation. It
also provides functionality to clear the input and results. Each calculation checks for
valid input and informs the user accordingly.

You might also like