terry terry - 20 days ago 8
Python Question

unsupported operand type "float" and "str"

i'm trying to print the operation however the first statement is working but second statement has error.

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)

Answer

The problem here is that the variable totalCycle is of type float. Python does not know what it means to do + between a type float and string (because " * " is a string).

To do it the way you showed you have to convert totalCycle to string first, like this:

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