Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #! /usr/bin/env python3.2
- # -*- coding: utf-8 -*-
- # main.py
- """ Task: Exercise 4.7:
- Rewrite the grade program from the previous chapter using a function called
- computegrade that takes a score as its parameter and returns a grade as a
- string.
- Score Grade
- > 0.9 A
- > 0.8 B
- > 0.7 C
- > 0.6 D
- <= 0.6 F
- Program Execution:
- Enter score: 0.95
- A
- Enter score: perfect
- Bad score
- Enter score: 10.0
- Bad score
- Enter score: 0.75
- C
- Enter score: 0.5
- F
- Run the program repeatedly to test the various different values for input.
- """
- # Functions
- def determine_grade(score):
- """
- Determines the grade of a given score (string or float/int)
- Returns grade
- """
- grade = None
- try:
- score = float(score)
- if score < 0.0 or score > 1.0:
- raise 1 # simulates an error
- elif score > 0.9:
- grade = "A"
- elif score > 0.8:
- grade = "B"
- elif score > 0.7:
- grade = "C"
- elif score > 0.6:
- grade = "D"
- elif score >= 0:
- grade = "F"
- else:
- raise 1 # simulates an error
- except:
- grade = "Bad score"
- return grade
- # Main
- loop = True
- while loop:
- score = None
- grade = None
- # Enter score
- while score == None:
- try:
- score = float(input("Enter score: "))
- except ValueError:
- score = None
- print("Invalid value!")
- continue
- except:
- score = None
- print("Error")
- continue
- if score < 0 or score > 1:
- score = None
- print("Please enter a value between 0.0 and 1.0!")
- continue
- grade = determine_grade(score)
- print("The grade of " + str(score) + " is " + str(grade) + ".\n")
- print("Do you want to enter a new score?")
- try:
- choice = input("(Y/N): ")
- except:
- choice = 'N'
- if choice.upper() == 'Y' or choice.upper() == 'YES':
- # 'y', 'Y', 'yes', 'yEs', ... 'YES' are valid
- continue
- else: # everything else is invalid
- loop = False # and stops the program
- # test
- print("\nTesting string parameter in determine_grade(score):")
- print("Score: 0.815\t\tResult: " + str(determine_grade("0.815")))
- print("Score: 1.337\t\tResult: " + str(determine_grade("1.337")))
- print("Score: lagerregal\tResult: " + str(determine_grade("lagerregal")))
- print("Score: -0.02\t\tResult: " + str(determine_grade("-0.02")))
- print("Score: 0.699999999\tResult: " + str(determine_grade("0.699999999")))
- print("Score: 0.700000001\tResult: " + str(determine_grade("0.700000001")))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement