如何计算python中的百分比

问题描述 投票:8回答:7

这是我的计划

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

结果

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

但是,百分比结果是0。如何在Python中正确计算百分比?

python python-2.7 percentage
7个回答
11
投票

我想你正在学习如何使用Python。其他答案是对的。但我将回答你的主要问题:“如何计算python中的百分比”

虽然它按照你的方式工作,但看起来并不像pythonic。此外,如果您需要添加新主题会发生什么?你必须添加另一个变量,使用另一个输入,等等。我猜你想要所有标记的平均值,所以你每次添加新标记时都必须修改主题的数量!好像很乱......

我会抛出一段代码,你唯一需要做的就是在列表中添加新主题的名称。如果您试图理解这段简单的代码,那么您的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你可以测试代码并进行实验。


6
投票

你正在进行整数除法。在数字文字中附加.0

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

在Python 2.7中划分100/500==0

正如@unwind指出的那样,float()调用是多余的,因为float的乘法/除法返回一个浮点数:

per= tota*100.0 / 500

2
投票

这是因为(100/500)是一个整数表达式,产生0。

尝试

per = 100.0 * tota / 500

不需要float()调用,因为使用浮点文字(100.0)无论如何都会使整个表达式成为浮点数。


2
投票

对我有用的百分比计算:

(new_num - old_num) / old_num * 100.0

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)

注意:raw_input()函数用于从控制台获取输入及其返回字符串格式化值。所以我们需要转换成整数,否则会给出转换错误。


0
投票

我知道我迟到了,但如果你想知道最简单的方法,你可以这样做一个代码:

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

您可以更改数字分数和right_questions。它会告诉你百分比。


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 %
© www.soinside.com 2019 - 2024. All rights reserved.