Need to create GPA Calculator to run in command line

276 Views Asked by At

Need to write a GPA calculator using the provided dictionary to output the gpa based on the 4 arguments of letter grades. I can get the code to run in google colab or other IDEs, but I get no output in CL. Can someone point me to what I am missing?

''' import sys

#print (sys.argv[1])
#print (sys.argv[2])
#print (sys.argv[3])
#print (sys.argv[4])


def gpa_calculator():
  grades = [sys.argv[1], sys.argv[2], sys.argv[3], sys.argv[4]]
  grades_upper = [each_string.upper() for each_string in grades]
  points = 0
  grade_chart = {'A':4.0, 'A-':3.66, 'B+':3.33, 'B':3.0, 'B-':2.66,
                 'C+':2.33, 'C':2.0, 'C-':1.66, 'D+':1.33, 'D':1.00, 'D-':.66, 'F':0.00}
  for grade in grades_upper:
    points += grade_chart[grade]
  gpa = points / len(grades)
  rounded_gpa = round(gpa,2)
  return rounded_gpa
  print (rounded_gpa)

gpa_calculator()'''
2

There are 2 best solutions below

1
Mustafa Quraish On
return rounded_gpa
print (rounded_gpa)

You seem to be returning the value from the function before you reach the print statement. I'm guessing the value is returned correctly, but you don't do anything with the return value when calling the function, so nothing is output to the screen.

You should move the print(...) call above the return statement, or print out the result when calling the function:

print(gpa_calculate())
0
Kristian On

That's because you return first before print.

In jupyter notebook like google colab, each cell will print anything the last line returns (if any). That's why in such environment you get output.

Corrected code:

import sys

#print (sys.argv[1])
#print (sys.argv[2])
#print (sys.argv[3])
#print (sys.argv[4])


def gpa_calculator():
  grades = [sys.argv[1], sys.argv[2], sys.argv[3], sys.argv[4]]
  grades_upper = [each_string.upper() for each_string in grades]
  points = 0
  grade_chart = {'A':4.0, 'A-':3.66, 'B+':3.33, 'B':3.0, 'B-':2.66,
                 'C+':2.33, 'C':2.0, 'C-':1.66, 'D+':1.33, 'D':1.00, 'D-':.66, 'F':0.00}
  for grade in grades_upper:
    points += grade_chart[grade]
  gpa = points / len(grades)
  rounded_gpa = round(gpa,2)
  print(rounded_gpa)
  return rounded_gpa

gpa_calculator()

output:

C:\Users\XXXXX\Desktop>python3 a.py A B C D
2.5

C:\Users\XXXXX\Desktop>python3 a.py A A A A
4.0