Python:
import random
from tabulate import tabulate
select the marks
gradePoints = {“A”:4,”B”:3,”C”:2,”D”:1,”F”:0}
courseList = [“CST 161″,”Mat 144″,”ENG 201″,”PSY 101″,”HIS 101”]
gradeList = [“A”,”B”,”C”,”D”,”F”]
creditList = [3,4]
data = []
total_credit = 0
sums = 0
input the number of course that you want to select randomly
n = int(input(“Enter the number of courses : “))
for i in range(n):
  temp = []
  #for courses
  k = random.randint(0,4)
  temp.append(courseList[k])
  #for credits
  k = random.randint(0,1)
  total_credit += creditList[k]
  temp.append(creditList[k])
  #for grades
  k = random.randint(0,4)
  temp.append(gradeList[k])
  #for gradepoints
  sums += gradePoints[gradeList[k]] * temp[1]
  temp.append(gradePoints[gradeList[k]] * temp[1])
  data.append(temp)
print(tabulate(data,headers = [“Course”,”Credits”,”Grade”,”Value Per Course”]))
print(f”Total credits taken: {total_credit}”)
print(f”Total quality points earned : {sums}”)
The Correct Answer and Explanation is :
Explanation:
- Imports and Initialization:
- The code uses
randomto select courses, grades, and credits randomly, andtabulateto format the output into a table. gradePointsstores the numeric values for letter grades, where A=4, B=3, etc.courseList,gradeList, andcreditListdefine the courses, possible grades, and credit hours that will be used for the random selection.
- Data Collection:
- The user is prompted to input the number of courses they want to select.
- A loop runs
ntimes, selecting a course, credit hours, and grade randomly for each iteration. For each course selected, its grade points (calculated asgradePoints[grade] * credit) are accumulated in the variablesums. - The total credit hours (
total_credit) are also accumulated.
- Tabulate Output:
- The
tabulate()function is used to present the data in a neat tabular format with headers for each column: “Course”, “Credits”, “Grade”, and “Value Per Course.”
- Calculation of Total Credits and Quality Points:
- Finally, after the loop, the total number of credits and total quality points earned are displayed.
Key Fixes:
- Indentation Issues: Python is very sensitive to indentation. The original code had strange characters (
ÂÂ) and inconsistent indentation, which have been fixed. - Correct Calculation of Grade Points: The grade points for each course are now correctly calculated by multiplying the credit hours with the grade’s corresponding value.
- Fixed Looping and Data Appending: Ensured that data was being correctly appended into the
datalist.
This code simulates selecting random courses, grades, and credits, and then calculates and displays the total credits and grade points.