2016-11-15 4 views
0

Я пытаюсь распечатать операцию, но первый оператор работает, но второй оператор имеет ошибку.неподдерживаемый тип операнда «float» и «str»

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) 
+1

печати ("Общее количество потраченного = {0}". format (totalSpent)) или «Total cycle request = {0}». format (totalCycle) –

+0

Я думаю, это потому, что вы пытаетесь объединить float со строкой. Попробуйте 'print (str (totalCycle) +" * "+ str (reqSecond))' – LismUK

ответ

1

проблема здесь состоит в том, что переменная totalCycle имеет тип поплавка. Python не знает, что это значит сделать + между типом флоат и строки (потому что " * " является строка).

Чтобы сделать это так, как вы показали, вы должны преобразовать totalCycle в строку первым, как это:

print (str(totalCycle) + " * " + reqSecond) 
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'.