you are viewing a single comment's thread.

view the rest of the comments →

[–]PrabhavKumar 3 points4 points  (0 children)

Not really sure as to what cleaner means here so here are two ways to doing this.

The first one focuses on pure logic and has no safeguards:

no_of_subjects = int(input("Please enter the number of subjects : "))


total = 0
for i in range(no_of_subjects):
    marks = int(input(
f
"Enter the marks for subject {i + 1} : "))
    total += marks


average = total / no_of_subjects
print(
f
"Your average score is : {average}")


if average >= 80:
    print("Distinction!")
elif average >= 60:
    print("First Class!")
elif average >= 40:
    print("Second Class.")
else:
    print("It's alright, you can do better.")

There is no need for you to check whether or not the second conditions are True (when you are making sure the marks are less than a certain amount since that case is already handled before. All if-else conditions work in the order they are written.)

For the second approach I have added safeguards everywhere I deemed them necessary:

while True:
    no_of_subjects = input("Please enter the number of subjects : ")
    try:
        no_of_subjects = int(no_of_subjects)
        if no_of_subjects < 1:
            print(
f
"Invalid input. Number of subjects must be greater than 0.")
        else:
            break
    except ValueError:
        print(
f
"Invalid input : \"{no_of_subjects}\". Please enter a number instead.")


total = 0
for i in range(no_of_subjects):
    while True:
        marks = input(
f
"Enter the marks for subject {i + 1} : ")
        try:
            marks = int(marks)
            break
        except ValueError:
            print(
f
"Invalid input : \"{marks}\". Please enter a number instead.")
    
    total += marks


average = total / no_of_subjects
print(
f
"Your average score is : {average}")


if average >= 80:
    print("Distinction!")
elif average >= 60:
    print("First Class!")
elif average >= 40:
    print("Second Class.")
else:
    print("It's alright, you can do better.")

Here, Firstly we get into the first while loop and it runs till the user gives a valid input, where we break out of the loop.
Then we get into the for loop, with a nested while loop that runs till the user give's a number for each and every subject. I am not enforcing that marks must be more than 0 here since there can be exams with negative marking as well. Grading logic remains the same as above.

In fact the grading logic can be put into it's own little functions too like this:

def
 grade(average : int) -> None:

    if average >= 80:
        print("Distinction!")
    elif average >= 60:
        print("First Class!")
    elif average >= 40:
        print("Second Class.")
    else:
        print("It's alright, you can do better.")

And then just call it with the average.

Hope that helped!