0
mark=input("Please enter the mark you received for the test:")
total=input("Please enter the mark the test was out of:")

percentage=(mark*100/total)

print("Your percentage is:"),percentage,"%"

当我在 python 3.3.2 mac 中运行它时,会出现这个错误。

Traceback (most recent call last):
  File "/Users/user1/Desktop/Percentage2.py", line 4, in <module>
    percentage=(mark/total*100)
TypeError: unsupported operand type(s) for /: 'str' and 'str'

我该如何解决?

4

3 回答 3

6
percentage=(float(mark)*100/float(total))

print("Your percentage is: ",percentage,"%", sep='')
于 2013-08-15T11:05:52.520 回答
3

输入返回一个字符串,您正在尝试执行“30”*100/total,字符串无法进行数学计算,请尝试 int(mark) 和 int(total),然后进行数学运算。

try:
    Mark = int(input("Please enter the mark you received for the test."))
    Total = int(input("Please enter the mark the test was out of."))
    Perc = (Mark*100) / Total
    print("Your Percentage is"+Perc)
except:
    print("Numbers not entered. Please try again")
于 2013-08-15T11:09:56.443 回答
0

当您进行“打印”声明时,请执行以下操作:

print ("your percentage is: %p" % (percentage))

此外,您可以使用格式:

print("your percentage is: {0} ".format(percentage))

个人推荐使用格式。

于 2013-08-15T11:02:47.310 回答