0
Why use str func to assigned varaible?
elif user_input=="add": a = float (input ("enter a number: ")) b = float (input (" enter another number: ")) result = a + b print (" the result is" + result) this code should compute right?? but it computes only when result = str(a + b) or print( " the result is " + str(result)) my confusion is why use str when both a & b are float type and its addition should give me direct result!! Pls clarify
4 ответов
+ 3
@Jay:
raw_input is for Python 2.x
In Python 3, no need ( and no existence ) of this function ^^
@Sk Maidur:
In Python, you cannot concatenate ( + ) string with other types directly ( implicit casting ), you need to explicitly cast your variables, else you get an error from Python interpreter. That's as is... you need a and b to be float for being able to nuerically addition them, and you need result to be string to be printed with your ' the result is " string... ( but you can do other ways to reach the same result: the fact here is the ability to concatenate strings )
+ 1
You aren't supposed to use concatenation that way . Code that would work would be something like :
user_input = 'add'
if user_input=="add":
a = float (input ("enter a number: "))
b = float (input (" enter another number: "))
result = a + b
print (" the result is:", result)
0
instead is using input , try raw_input . Your code worked for me when I made that change .
0
@visph.....Thank you, I forgot about concatenation part while writing the code!!!