不支持的操作数类型“float”和“str”

时间:2016-11-15 17:04:20

标签: python python-2.7 operators

我正在尝试打印操作,但第一个语句正在运行但第二个语句有错误。

conSwitch = raw_input("Enter cycle of context switch: ")
cycleOpr = raw_input("Enter cycle operation: ")

totalCycle = float(conSwitch) + float(cycleOpr) + float(conSwitch)

print "Context =", conSwitch
print "Cycle operation =", cycleOpr
print "Context switch back =", conSwitch
print("\n")

print (conSwitch + " + " + cycleOpr + " + " + conSwitch)
print ("Total number of cycle is: " + format(totalCycle))
print("===================================================")

reqSecond = raw_input("Enter cycle request second:")

print "Total cycle request =", totalCycle
print "Cycle request per second =", reqSecond
print("\n")

totalSpent = float(totalCycle) * float(reqSecond)
print (totalCycle + " * " + reqSecond)
print ("Total number of spent = " + format(totalSpent))

=============================================== ===============

First statement
Work===>> print (conSwitch + " + " + cycleOpr + " + " + conSwitch)

Second statement
Error===>> print (totalCycle + " * " + reqSecond)

2 个答案:

答案 0 :(得分:1)

这里的问题是变量totalCycle的类型为 float 。 Python不知道在类型 float 字符串之间执行 + 意味着什么(因为" * "字符串)。

要按照您展示的方式执行此操作,您必须首先将totalCycle转换为字符串,如下所示:

print (str(totalCycle) + " * " + reqSecond)

答案 1 :(得分:0)

FORMAT Syntax

"First, thou shalt count to {0}"  # References first positional argument
"Bring me a {}"                   # Implicitly references the first positional argument
"From {} to {}"                   # Same as "From {0} to {1}"
"My quest is {name}"              # References keyword argument 'name'
"Weight in tons {0.weight}"       # 'weight' attribute of first positional arg
"Units destroyed: {players[0]}"   # First element of keyword argument 'players'.