0% found this document useful (0 votes)
4 views5 pages

Grade 7 analysis tool

The document contains a Python script that generates an Excel workbook for analyzing student grades. It includes functions to create sample student data, determine grades based on standardized scores, and visualize the results with charts. The workbook consists of three sheets: Student Scores, Summary, and Dashboard, providing a comprehensive overview of student performance and grade distribution.

Uploaded by

Patrick Kamfwa
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views5 pages

Grade 7 analysis tool

The document contains a Python script that generates an Excel workbook for analyzing student grades. It includes functions to create sample student data, determine grades based on standardized scores, and visualize the results with charts. The workbook consists of three sheets: Student Scores, Summary, and Dashboard, providing a comprehensive overview of student performance and grade distribution.

Uploaded by

Patrick Kamfwa
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 5

import openpyxl

from openpyxl.styles import Font, Alignment, Border, Side, PatternFill, Color


from openpyxl.chart import (
BarChart, Reference, Series,
PieChart, DoughnutChart,
ProjectedPieChart
)
from openpyxl.chart.label import DataLabelList
import random

def get_grade_color(grade):
"""
Assign colors to different grades.

Args:
grade (str): Grade of the student

Returns:
PatternFill: Color fill for the grade
"""
grade_colors = {
'ONE': PatternFill(start_color='00FF00', end_color='00FF00',
fill_type='solid'), # Green
'TWO': PatternFill(start_color='92D050', end_color='92D050',
fill_type='solid'), # Lime Green
'THREE': PatternFill(start_color='FFC000', end_color='FFC000',
fill_type='solid'), # Orange
'FOUR': PatternFill(start_color='FFA500', end_color='FFA500',
fill_type='solid'), # Dark Orange
'FAIL': PatternFill(start_color='FF0000', end_color='FF0000',
fill_type='solid'), # Red
'X': PatternFill(start_color='808080', end_color='808080',
fill_type='solid') # Gray
}
return grade_colors.get(grade, PatternFill())

def generate_student_data(num_students=30):
"""
Generate sample student data for the assessment.

Args:
num_students (int): Number of students to generate. Defaults to 30.

Returns:
list: List of student dictionaries with name, sex, and test score
"""
first_names_male = ['John', 'Michael', 'David', 'James', 'Robert', 'William',
'Daniel', 'Matthew', 'Joseph', 'Christopher']
first_names_female = ['Emma', 'Olivia', 'Sophia', 'Isabella', 'Ava', 'Mia',
'Charlotte', 'Amelia', 'Harper', 'Evelyn']
last_names = ['Smith', 'Johnson', 'Williams', 'Brown', 'Jones', 'Garcia',
'Miller', 'Davis', 'Rodriguez', 'Martinez']

students = []
for i in range(num_students):
# Randomly choose sex
sex = random.choice(['M', 'F'])

# Randomly choose first name based on sex


if sex == 'M':
first_name = random.choice(first_names_male)
else:
first_name = random.choice(first_names_female)

# Randomly choose last name


last_name = random.choice(last_names)

# Generate random test score (0-60)


test_score = random.randint(0, 60)

students.append({
'SN': i + 1,
'Name': f"{first_name} {last_name}",
'Sex': sex,
'Test Score': test_score
})

return students

def determine_grade(standardized_score):
"""
Determine grade based on standardized score.

Args:
standardized_score (float): Standardized test score

Returns:
tuple: (Grade, Description)
"""
if standardized_score >= 112:
return ('ONE', 'EXCELLENT')
elif 90 <= standardized_score < 112:
return ('TWO', 'VERY GOOD')
elif 75 <= standardized_score < 90:
return ('THREE', 'GOOD')
elif 40 <= standardized_score < 75:
return ('FOUR', 'AVERAGE')
elif standardized_score < 40:
return ('FAIL', 'BELOW AVERAGE')
else:
return ('X', 'ABSENT')

def create_grade_analysis_workbook():
"""
Create an Excel workbook for grade analysis with dashboard.
"""
# Create a new workbook
wb = openpyxl.Workbook()

# Rename the first sheet


ws1 = wb.active
ws1.title = 'Student Scores'

# Create the second sheet for summary


ws2 = wb.create_sheet(title='Summary')

# Create the third sheet for dashboard


ws3 = wb.create_sheet(title='Dashboard')
# Headers for the first sheet
headers1 = ['SN', 'Name', 'Sex', 'Test Score', 'Standardized Score', 'Grade',
'Description']
for col, header in enumerate(headers1, start=1):
ws1.cell(row=1, column=col, value=header)
ws1.cell(row=1, column=col).font = Font(bold=True)

# Generate student data


students = generate_student_data()

# Populate first sheet with student data


results_by_gender = {
'M': {'ONE': 0, 'TWO': 0, 'THREE': 0, 'FOUR': 0, 'FAIL': 0, 'X': 0,
'Total': 0},
'F': {'ONE': 0, 'TWO': 0, 'THREE': 0, 'FOUR': 0, 'FAIL': 0, 'X': 0,
'Total': 0},
'Total': {'ONE': 0, 'TWO': 0, 'THREE': 0, 'FOUR': 0, 'FAIL': 0, 'X': 0,
'Total': 0}
}

for row, student in enumerate(students, start=2):


# Calculate standardized score
standardized_score = student['Test Score'] * 2.5

# Determine grade
grade, description = determine_grade(standardized_score)

# Populate row with student data


ws1.cell(row=row, column=1, value=student['SN'])
ws1.cell(row=row, column=2, value=student['Name'])
ws1.cell(row=row, column=3, value=student['Sex'])
ws1.cell(row=row, column=4, value=student['Test Score'])
ws1.cell(row=row, column=5, value=round(standardized_score, 2))
grade_cell = ws1.cell(row=row, column=6, value=grade)
ws1.cell(row=row, column=7, value=description)

# Color code the grade cell


grade_cell.fill = get_grade_color(grade)

# Track results by gender


sex = student['Sex']
results_by_gender[sex][grade] += 1
results_by_gender[sex]['Total'] += 1
results_by_gender['Total'][grade] += 1
results_by_gender['Total']['Total'] += 1

# Create summary sheet


summary_headers = [
'Category', 'Total Students',
'Grade ONE', 'Grade TWO', 'Grade THREE',
'Grade FOUR', 'FAIL', 'ABSENT',
'Pass Percentage'
]
ws2.append(summary_headers)
for cell in ws2[1]:
cell.font = Font(bold=True)

# Gender-wise summary
for sex in ['M', 'F', 'Total']:
row_data = [
f"{sex} Students",
results_by_gender[sex]['Total'],
results_by_gender[sex]['ONE'],
results_by_gender[sex]['TWO'],
results_by_gender[sex]['THREE'],
results_by_gender[sex]['FOUR'],
results_by_gender[sex]['FAIL'],
results_by_gender[sex]['X'],
f"{round((results_by_gender[sex]['ONE'] + results_by_gender[sex]['TWO']
+ results_by_gender[sex]['THREE']) / results_by_gender[sex]['Total'] * 100, 2)}%"
if results_by_gender[sex]['Total'] > 0 else "0%"
]
ws2.append(row_data)

# Grouped Bar Chart for Grades by Gender (Count)


grade_order = ['ONE', 'TWO', 'THREE', 'FOUR', 'FAIL', 'X']

# Prepare data for bar chart


bar_data = [
[results_by_gender['M'][grade] for grade in grade_order],
[results_by_gender['F'][grade] for grade in grade_order]
]

# Create Grouped Bar Chart for Grade Counts


bar_chart = BarChart()
bar_chart.type = "col"
bar_chart.style = 10
bar_chart.title = "Grades Distribution by Gender (Count)"
bar_chart.y_axis.title = 'Number of Students'
bar_chart.x_axis.title = 'Grades'

# Create data references


data = openpyxl.chart.Reference(ws2, min_col=3, max_col=8, min_row=1,
max_row=3)
cats = openpyxl.chart.Reference(ws2, min_col=1, max_col=1, min_row=2,
max_row=3)

bar_chart.add_data(data, titles_from_data=True)
bar_chart.set_categories(cats)

# Grouped Bar Chart for Grades Percentage


percentage_bar_chart = BarChart()
percentage_bar_chart.type = "col"
percentage_bar_chart.style = 10
percentage_bar_chart.title = "Grades Distribution by Gender (Percentage)"
percentage_bar_chart.y_axis.title = 'Percentage of Students'
percentage_bar_chart.x_axis.title = 'Grades'

# Calculate percentages
percentage_data = [
[round(results_by_gender['M'][grade] / results_by_gender['M']['Total'] *
100, 2) for grade in grade_order],
[round(results_by_gender['F'][grade] / results_by_gender['F']['Total'] *
100, 2) for grade in grade_order]
]

# Pie Chart for Grades ONE to THREE


pie_chart1 = DoughnutChart()
pie_chart1.title = "Percentage of Grades ONE to THREE"
pie_data1 = [
results_by_gender['Total']['ONE'],
results_by_gender['Total']['TWO'],
results_by_gender['Total']['THREE']
]
pie_cats1 = ['Grade ONE', 'Grade TWO', 'Grade THREE']

# Pie Chart for Grades FOUR and FAIL


pie_chart2 = DoughnutChart()
pie_chart2.title = "Percentage of Grades FOUR and FAIL"
pie_data2 = [
results_by_gender['Total']['FOUR'],
results_by_gender['Total']['FAIL']
]
pie_cats2 = ['Grade FOUR', 'FAIL']

# Place charts on dashboard


ws3.add_chart(bar_chart, "B2")
ws3.add_chart(percentage_bar_chart, "B20")
ws3.add_chart(pie_chart1, "R2")
ws3.add_chart(pie_chart2, "R20")

# Auto-adjust column widths for both sheets


for sheet in [ws1, ws2, ws3]:
for col in sheet.columns:
max_length = 0
column = col[0].column_letter
for cell in col:
try:
if len(str(cell.value)) > max_length:
max_length = len(cell.value)
except:
pass
adjusted_width = (max_length + 2)
sheet.column_dimensions[column].width = adjusted_width

# Save the workbook


wb.save('Grade_7_Assessment_Analysis.xlsx')
print("Excel file 'Grade_7_Assessment_Analysis.xlsx' has been created
successfully!")

# Run the analysis


create_grade_analysis_workbook()

You might also like