0
Why are we using str for adding to numbers...?
we are taking inputs as interger and storing them in variables num1 and num2...during addition the numbers input by the user should pass in the variables...so where the use to convert it to string...what is the use of str???
10 Réponses
+ 2
If you want to do:
n = 42
s = "the answer is: "
print( s + n )
... in Python, you'll get an error, as you can't concatenate a string and another type.
So, one solution, is to explicitly cast the other type with the str() function:
print( s + str( n ) ) # edited: typo mistake ^^ ( 'int' instead 'str' -- thank's to @ramzi )
+ 2
One very important basic rule in Python is that you cant add a string and a non-string. So you need the same type. You can convert numbers/integers etc. into strings very easily but you cant convert every string to a number/etc.
+ 2
To store the RESULT of the addition: doing the cast outside the function call instead of inside: this is ( quiet ) the same as what's doing interternaly in both cases ;)
+ 2
@Raj Kumar Chauhan:
No one said than you cannot:
print(42)
...but that you cannot:
print("answer is "+42)
It's not a question about the print() fuction, but about the concatenation of strings...
print() is used only to show result, but you also cannot do:
s = "answer is " + 42
... no more ^^
+ 1
@visph
in your comment starting with "if you want to do: ", at the end of the code you typed print(s+int(n)). this does NOT work. it should be replaced with print(s+str(n)). please re-edit your post because it can be misguiding
0
thank you but I am still confused...sorry...in the demonstration it is given-
elif user_input == "add":
num1 = float(input("Enter a number: "))
num2 = float(input("Enter another number: "))
result = str(num1 + num2)
print("The answer is " + result)
here we are taking float as tge number in variable num1 and num2 lets say user input 1 and 2 respectively...now in result which is another variable we are doing addition...so in
result= str(num1+num2) the value inputted in variables num1 and num2 should pass here and get added...so why we are using str...is it to store the addition in string form...???
0
god...i got it... thanks 😊👍
0
I dont think in python you need to explicitly write data type of result. It will automatically convert to suitable data type based on result.
0
yes it's like you said in the end, it's to store the result in a string form so that print("The answer is "+result) doesn't make an error
0
@visph I didn't say we can not. I said it's not mandatory unless you specifically want to specify in which data type you want to store result.