Jot*_*ani 9 python percentage python-2.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
Run Code Online (Sandbox Code Playgroud)
结果
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
Run Code Online (Sandbox Code Playgroud)
但是,百分比结果是0.如何在Python中正确计算百分比?
小智 12
我想你正在学习如何使用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))
Run Code Online (Sandbox Code Playgroud)
在这里,您可以测试代码并进行实验.
你正在进行整数除法.附加.0数字文字:
per=float(tota)*(100.0/500.0)
Run Code Online (Sandbox Code Playgroud)
在Python 2.7中划分100/500==0.
正如@unwind指出的那样,float()调用是多余的,因为float的乘法/除法返回一个浮点数:
per= tota*100.0 / 500
Run Code Online (Sandbox Code Playgroud)
这是因为(100/500)是一个整数表达式,结果为 0。
尝试
per = 100.0 * tota / 500
Run Code Online (Sandbox Code Playgroud)
不需要调用float(),因为使用浮点文字 ( 100.0) 无论如何都会使整个表达式成为浮点。
| 归档时间: |
|
| 查看次数: |
79410 次 |
| 最近记录: |