Skip to content

Instantly share code, notes, and snippets.

@alyoshenka
Created January 25, 2023 03:29
Show Gist options
  • Save alyoshenka/9d7467bfcebea85b97e0450da7d87bb5 to your computer and use it in GitHub Desktop.
Save alyoshenka/9d7467bfcebea85b97e0450da7d87bb5 to your computer and use it in GitHub Desktop.
Percentage Range to GPA - Python

Percentage Range to GPA - Python

How to use this program:

  1. Run with Python: python[3] main.py
  2. Input a grade percentage (0 to 100, inclusive, no symbols, decimals accepted)
  3. The program will return the GPA for that percentage
def percent_to_gpa(percent):
"""Convert a percentage (0 to 100) to a GPA"""
if percent >= 95:
return 4.0
elif percent < 65:
return 0.0
else:
# rounds down to 1 decimal place
return int((4 - (95-percent)/10.0) * 10) / 10.0
def is_valid_range(percent):
"""Check that a given percentage is within valid range (0 to 100 inclusive)"""
return percent >= 0 and percent <= 100
def prompt():
"""Prompt for a grade percentage"""
return input("--- Input a grade percentage ([0 to 100], q to quit): ")
def test():
"""Test the program with boundary inputs"""
assert percent_to_gpa(95) == 4.0
assert percent_to_gpa(65) == 1.0
assert percent_to_gpa(64.9) == 0.0
assert percent_to_gpa(87) == 3.2
assert percent_to_gpa(73.1) == 1.8
assert percent_to_gpa(72.9) == 1.7
def main():
"""Prompts the user for percentages until they decide to quit"""
text = prompt()
while text != 'q':
try:
percent = float(text)
if is_valid_range(percent):
print('GPA:', percent_to_gpa(percent))
else:
print('***', percent, 'is out of range [0 to 100]')
except Exception as e:
print('*** Unable to parse', text, ': ', e)
text = prompt()
print('*** Exiting')
test()
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment