如何在 Python 中计算百分比

问题描述

我正在用 Python 编写一个程序来确定我在各个科目中的分数百分比。它应该询问我的分数并找到百分比,但出了点问题。我还年轻,所以请不要嘲笑我的尝试:

import os
import time
print ("This is a program to calculate your percentage in your ACADEMICS ")
time.sleep(2)

english = input("Enter your english marks \n \t")
time.sleep(1)

maths = input ("Enter your maths marks \n \t")
time.sleep(1)

science= input ("Enter your science marks \n \t")
time.sleep(1)

print ("OK,i am reviewing your marks,")
time.sleep(1)
print ("Hmm,verry poor marks,but here is your %")

percentage = english + maths + science /3
print(percentage)

但最后它说

Traceback (most recent call last):
  File "C:/Users/COOL BOY/Desktop/percentage.py",line 18,in <module>
    percentage = english + maths + science %3
TypeError: not all arguments converted during string formatting

在这里做错了什么?

解决方法

input 函数返回一个字符串。 在计算 english + maths + science /3 时,您正在添加字符串! 您应该通过 int(string)float(string) 函数将输入转换为数字。 您还可以使用 'mystring'.isdigit() 检查您的字符串是否由数字组成。

,

在要求输入时将字符串转换为整数,计算时使用字符串而不是整数。

{
  "type": "node","request": "launch","name": "Jest All","program": "${workspaceFolder}/node_modules/.bin/jest","args": [
    "--runInBand"
  ],"console": "integratedTerminal","internalConsoleOptions": "neverOpen","disableOptimisticBPs": true,"windows": {
    "program": "${workspaceFolder}/node_modules/jest/bin/jest",}
},
,
  1. 输入应该由 int 转换,例如:int(input("number"))

  2. 考虑到科目的 MaxScore 为 100,公式为

    percentage=(aquaired marks of all 3 subjects)x100/(3*100)

  3. 百分比应四舍五入到最后 2 位数字。

最终的程序是。

import os
import time

maxscore = 100
totalsubjects=3

print ("This is a program to calculate your percentage in your ACADEMICS ")
time.sleep(2)


english = int(input("Enter your english marks \n \t"))
time.sleep(1)

maths = int(input("Enter your maths marks \n \t"))
time.sleep(1)


science= int(input("Enter your science marks \n \t"))
time.sleep(1)


print ("OK,i am reviewing your marks,")
time.sleep(1)
print ("Hmm,verry poor marks,but here is your %")

percentage = (english + maths + science)*100/(maxscore*totalsubjects)
print(round(percentage,2))
,

pythonic 方式

import os,time

def get_subject_score(sub):
    time.sleep(2)
    return int(input(f"Enter your {sub} marks : "))  # int or float as you wish

print("This is a program to calculate your percentage in your ACADEMICS")

english = get_subject_score("english")
maths = get_subject_score("math")
science = get_subject_score("science")

print(f"OK,{(english + maths + science) / 3}")
,
  1. 当您将 integrer 作为输入时,它应该是 int(input()) 而不是 input(),因为稍后将输入作为字符串
  2. 要计算百分比,它应该是百分比 =(获得标记的总和)最大标记/(3最大标记)

假设 100 分 *百分比 =(英语 + 数学 + 科学)100/(3*100)

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...