gpt4 book ai didi

python - 如何在python中计算百分比

转载 作者:太空狗 更新时间:2023-10-29 20:37:13 25 4
gpt4 key购买 nike

这是我的程序

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 中计算百分比”

虽然它按照您的方式工作,但它看起来并不像 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您可以测试代码并进行试验。

关于python - 如何在python中计算百分比,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22169081/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com