简体   繁体   中英

How to declare a variable/list with no int but still be able to divide with it?

I'm trying to code a program that calculates my grade average and I ran into a problem: I want to calculate the average like this:

mathslist = []

def gradesstart():
    mathsgrade = (sum(mathslist))/(len(mathslist))

    print('''Gradeoverview:

Maths: ''' + str(mathsgrade) )
    subject = input("For which subject you want to add a grade? ")

    if subject=="Maths":
         mathslist.append(int(input("Which grade you want to add? ")))

    print("Your grade overview has been updated!")
    gradesstart()

gradesstart()

But like this it says that it is not possible because you divide by zero. So I tried to give the list an element like 1 but than it crashes the grade average. Is there a way to solve this problem?

Edit: I solved my problem from above thanks to one of you but now i want to define two list (mathlistx1 for grades that are evaluated once anf mathlistx2 for grades that are evaluated twice) and i will define mathsgrade like this:

mathsgrade = (((sum(mathslistx1)-1)/(len(mathslistx1)-1))+(((sum(mathslistx2)-1)/(len(mathslistx2)-1))*2))/3

So now I have the same problem as above but with two lists. Just putting it in a if statement : if mathslistx1 and mathslistx2: doesn't work

Don't try to compute the grade if there is nothing in the list:

if mathslist:  # <- empty lists are falsy
    mathsgrade = sum(mathslist) / len(mathslist)
    print(f'Gradeoverview: Maths: {mathsgrade}')
subject = ...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM