how to calculate percentage in python
Asked Answered
A

10

18

This is my program

print" Welcome to NLC Boys Hr. Sec. School "
a=input("\nEnter the Tamil marks :")
b=input("\nEnter the English marks :")
c=input("\nEnter the Maths marks :")
d=input("\nEnter the Science marks :")
e=input("\nEnter the Social science marks :")
tota=a+b+c+d+e
print"Total is: ", tota
per=float(tota)*(100/500)
print "Percentage is: ",per

Result

Welcome to NLC Boys Hr. Sec. School 

Enter the Tamil marks :78

Enter the English marks :98

Enter the Maths marks :56

Enter the Science marks :65

Enter the Social science marks :78 Total is:  375 Percentage is:  0.0

However, the percentage result is 0. How do I calculate the percentage correctly in Python?

Anglicanism answered 4/3, 2014 at 10:19 Comment(1)
unrelated: if you have a fraction then to print it as percents: print "{:.0%}".format(sum(marks) / (len(marks) * perfect_mark * 1.0))Shelving
M
19

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.7

marks = {} #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 subject
for subject in subjects:
   marks[subject] = input("Enter the " + subject + " marks: ")

#and finally the calculation of the total and the average
total = 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.

Matusow answered 4/3, 2014 at 11:42 Comment(0)
B
8

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
Bertrando answered 4/3, 2014 at 10:20 Comment(0)
D
5

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.

Dorking answered 4/3, 2014 at 10:21 Comment(1)
@Dorking You're right about the float explicit conversion. I just included because copy pasted the OP's line. Fixing in my answer.Bertrando
S
2

Percent calculation that worked for me:

(new_num - old_num) / old_num * 100.0
Scrimmage answered 15/3, 2018 at 16:54 Comment(0)
H
0
marks = raw_input('Enter your Obtain marks:')
outof = raw_input('Enter Out of marks:')
marks = int(marks)
outof = int(outof)
per = marks*100/outof
print 'Your Percentage is:'+str(per)

Note : raw_input() function is used to take input from console and its return string formatted value. So we need to convert into integer otherwise it give error of conversion.

Hahn answered 23/6, 2017 at 13:13 Comment(0)
L
0

I know I am late, but if you want to know the easiest way, you could do a code like this:

number = 100
right_questions = 1
control = 100
c = control / number
cc = right_questions * c
print float(cc)

You can change up the number score, and right_questions. It will tell you the percent.

Lactary answered 10/4, 2018 at 23:57 Comment(0)
M
0
def percentage_match(mainvalue,comparevalue):
    if mainvalue >= comparevalue:
        matched_less = mainvalue - comparevalue
        no_percentage_matched = 100 - matched_less*100.0/mainvalue
        no_percentage_matched = str(no_percentage_matched) + ' %'
        return no_percentage_matched 
    else:
        print('please checkout your value')

print percentage_match(100,10)
Ans = 10.0 %
Montiel answered 16/4, 2019 at 5:24 Comment(0)
M
0

#Just begining my coding career with Python #here's what i wrote its simple

print("\nEnter your marks to calculate percentage")
a=float(input("\nEnter your English marks"))
b=float(input("\nEnter your Mathematics marks"))
c=float(input("\nEnter your Science marks"))
d=float(input("\nEnter your Computer Science marks"))
e=float(input("\nEnter your History marks"))
tot=a+b+c+d+e
print("\nTotal marks obtained",tot)
per=float(tot/500)*100
print("Percentage",per)
Muzzy answered 4/1, 2022 at 13:7 Comment(0)
F
0

You can try the below function using part == total marks out of whole == 500.

def percentage(part, whole):
try:
    if part == 0:
        percentage = 0
    else:
        percentage = 100 * float(part) / float(whole)
    return "{:.0f}".format(percentage)
except Exception as e:
    percentage = 100
    return "{:.0f}".format(percentage)
Fredra answered 22/2, 2022 at 13:55 Comment(0)
P
0
import random

#find percentage of the amount and print the result. Example: 30.0% of 500.0 = ???
def PercentOfAmount(fPercentage, fAmount):
    print(str(fPercentage) + "% of " + str(fAmount) + " = " + str(fPercentage / 100.0 * fAmount))

#nChance represents a % chance from 1-100.
def PercentChance(nChance):
    nRandom = int(random.randrange(1, 101))
    if nChance < 1 or nChance > 100: #Return False if nChance is below 1 or above 100.
         print("nChance returns False below 1 or above 100")
         return False
    if nRandom <= nChance: #if random 1-100 is less than or equal to nChance return True.
         return True
    else:
         return False
Phenanthrene answered 12/3, 2023 at 1:37 Comment(2)
A couple useful functions for percentages.Phenanthrene
As it’s currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.Biltong

© 2022 - 2024 — McMap. All rights reserved.