简体   繁体   English

如何计算 python 中的百分比

[英]how to calculate percentage in python

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 .但是,百分比结果为0 How do I calculate the percentage correctly in Python?如何正确计算 Python 中的百分比?

I guess you're learning how to Python.我猜你正在学习如何使用 Python。 The other answers are right.其他答案都对。 But I am going to answer your main question: "how to calculate percentage in python"但我要回答你的主要问题:“如何在 python 中计算百分比”

Although it works the way you did it, it doesn´t look very pythonic.尽管它按照您的方式工作,但它看起来不是很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.如果你试图理解这段简单的代码,你的 Python 编码技能将会经历一些小插曲。

#!/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.您可以在此处测试代码并对其进行试验。

You're performing an integer division .您正在执行整数除法 Append a .0 to the number literals:.0附加到数字文字:

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

In Python 2.7 the division 100/500==0 .在 Python 2.7 中,除法100/500==0

As pointed out by @unwind, the float() call is superfluous since a multiplication/division by a float returns a float:正如@unwind 所指出的, float()调用是多余的,因为乘法/除法浮点数返回一个浮点数:

per= tota*100.0 / 500

This is because (100/500) is an integer expression yielding 0.这是因为(100/500)是一个产生 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.不需要float()调用,因为使用浮点文字 ( 100.0 ) 无论如何都会使整个表达式成为浮点。

对我有用的百分比计算:

(new_num - old_num) / old_num * 100.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.注意:raw_input() 函数用于从控制台获取输入及其返回字符串格式的值。 So we need to convert into integer otherwise it give error of conversion.所以我们需要转换成整数,否则会产生转换错误。

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.您可以更改数字分数和 right_questions。 It will tell you the percent.它会告诉你百分比。

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 %

#Just begining my coding career with Python #here's what i wrote its simple #刚刚开始我的 Python 编码生涯 #这里是我写的很简单

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)

You can try the below function using part == total marks out of whole == 500.你可以尝试下面的 function 使用 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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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