#!/usr/bin/env python # # Author : Ahmed Obied (amaobied@ucalgary.ca) # Date : Jan. 17th 2008 # Purpose : Calculates the percentage and letter grade of a given total # and mark to demonstrate the use of functions # def read_total_marks(): """ Purpose : prompts the user to enter in the total marks for the test. This function also does some basic error checking on the number entered. Returns : the number entered by the user """ end_loop = False while not end_loop: # get the total number of marks marks = float(raw_input('Enter the total number of marks: ')) # if it's less than zero then print an error if marks < 0: print 'Error: The number must be greater than zero.' else: # end he loop if we get a proper number end_loop = True return marks def read_users_mark(total_marks): """ Purpose : prompts the user to enter the mark they got for the test. This function also does some basic error checking on the number entered. Parameters : total_marks - the total number of possible marks on the test. This value is used for error checking Returns : the number entered by the user """ end_loop = False while not end_loop: # get the mark mark = float(raw_input('Enter your mark: ')) # if it's not in the range then print an error if mark < 0 or mark > total_marks: print 'Error: incorrect input' else: end_loop = True return mark def compute_percentage(total_marks, mark): """ Purpose : computes the percentage the user got Parameters : total_marks - the total number of possible marks on the test mark - the mark the user got on the test Returns : the percentage """ return mark * 100.0 / total_marks def find_letter_grade(percentage): """ Purpose : find the letter grade based upon a given percentage value Parameters : percentage - the percentage used to find the letter grade Returns : the letter grade as a string """ if percentage < 39.9: letter_grade = 'F' elif percentage < 44.0: letter_grade = 'D-' elif percentage < 49.0: letter_grade = 'D' elif percentage < 54.0: letter_grade = 'D+' elif percentage < 59.0: letter_grade = 'C-' elif percentage < 64.0: letter_grade = 'C' elif percentage < 69.0: letter_grade = 'C-' elif percentage < 74.0: letter_grade = 'B-' elif percentage < 79.0: letter_grade = 'B' elif percentage < 84.0: letter_grade = 'B+' elif percentage < 89.0: letter_grade = 'A-' else: letter_grade = 'A' return letter_grade if __name__ == '__main__': """ Main Entry """ # call a function to get the total marks total_marks = read_total_marks() # call a function to read the mark of the user mark = read_users_mark(total_marks) # call a function to calculate the percentage percentage = compute_percentage(total_marks, mark) # call a function to get the appropriate letter grade letter_grade = find_letter_grade(percentage) # print to the console with proper formatting print 'You got %.2f%c on the test which gives you a letter grade of %s' % \ (percentage, '%', letter_grade)