根据用户输入计算百分比

时间:2015-11-10 20:17:13

标签: python input percentage

我想创建一个程序来创建由用户输入决定的两个数字的百分比,如果你想找出你已经获得的百分比,可以使用它。一个测试等。这是我在python中使用的代码,但我继续收到错误消息

" TypeError:/:' str'不支持的操作数类型和' str'"

count = input("What is the amount of marks you got in your test?")
total = input("What is the total amount of marks in your test?")
percentage = count/total*100
print(percentage, + "%")

我听说过在python版本3.5.0上无法完成这个百分比,虽然我不知道这是不是真的。

我正在运行Windows 10和python 3.5.0

2 个答案:

答案 0 :(得分:0)

您需要将输入从string转换为float,因为输入的格式为string ...

在计算中使用它们之前,请执行此操作

count = float(count)
total = float(total)

答案 1 :(得分:0)

首先需要将count和total转换为浮点数:

while true:
    count = input("What is the amount of marks you got in your test?")
    total = input("What is the total amount of marks in your test?")

    try: #makes sure for valid input
         count = float(count)
         total = float(count)
         break
    except:
         print("Please input valid number")

然后您可以执行数字操作:

percentage = count/total*100 #valid
print(str(percentage) + "%")#you had a comma when you didnt need it, and you need to convert back to string before concatenating