how to calculate percentage in python how to calculate percentage in python python python

how to calculate percentage in python


I guess you're learning how to Python. The other answers are right. But I am going to answer your main question: "how to calculate percentage in python"

Although it works the way you did it, it doesn´t look very pythonic. Also, what happens if you need to add a new subject? You'll have to add another variable, use another input, etc. I guess you want the average of all marks, so you will also have to modify the count of the subjects everytime you add a new one! Seems a mess...

I´ll throw a piece of code where the only thing you'll have to do is to add the name of the new subject in a list. If you try to understand this simple piece of code, your Python coding skills will experiment a little bump.

#!/usr/local/bin/python2.7marks = {} #a dictionary, it's a list of (key : value) pairs (eg. "Maths" : 34)subjects = ["Tamil","English","Maths","Science","Social"] # this is a list#here we populate the dictionary with the marks for every subjectfor subject in subjects:   marks[subject] = input("Enter the " + subject + " marks: ")#and finally the calculation of the total and the averagetotal = sum(marks.itervalues())average = float(total) / len(marks)print ("The total is " + str(total) + " and the average is " + str(average))

Here you can test the code and experiment with it.


You're performing an integer division. Append a .0 to the number literals:

per=float(tota)*(100.0/500.0)

In Python 2.7 the division 100/500==0.

As pointed out by @unwind, the float() call is superfluous since a multiplication/division by a float returns a float:

per= tota*100.0 / 500


This is because (100/500) is an integer expression yielding 0.

Try

per = 100.0 * tota / 500

there's no need for the float() call, since using a floating-point literal (100.0) will make the entire expression floating-point anyway.