0

built in function error

1 x = 3 2 y= (x) + 3 3 print (y) >>> 6 1 x = input 2 y= (x) + 3 3 print (y) type: 3 >>>Traceback (most recent call last): File "..\Playground\", line 2, in <module> y= (x) + 3 TypeError: unsupported operand type(s) for +: 'builtin_function_or_method' and 'int' does anybody know what i need to do to make it work? can you tell me which section i should review more to prevent this? thanks in advance!

1st Jun 2017, 4:21 AM
kevin Pacheco
4 Respuestas
+ 2
also dont forget the parentheses after the input function. input() will always return what has written the user as a STRING and that's very importsnt because there is no logic to do "Salut" + 56, that's why python returns an error. There are several solutions : You can try to cast your text for example "45" (a string) might be understand as 45 (an integer) like this : a= int("45") # a is 45 here we use the int "function" to convert "45" to an integer. If you want to get any number not only they integers you should use float instead of int : a = float("4.5") # a is 4.5 Finally if you have a calculation as input for example the write "5+3*2", you can us the eval function that will evaluate the expreaaion as a calculation and will returns the result. a = eval("5+3*2") # a is 11 But be aware with all these functions, if the user writes something that is not correct you will get an error so you should use the try except blocks to handle to errors.
1st Jun 2017, 5:14 AM
Glozi30
Glozi30 - avatar
+ 1
input() function takes user input and always makes it a string. Since you tried to add an integer to a string, thus you received an error. As already mentioned you can convert user input to either float or integer like this: x = float(input()) or x = int(input()) To prevent this happening in the future: always check what types of data you're working with. If you don't know for sure, you can always check using type() function on any object
1st Jun 2017, 5:11 AM
Lana
Lana - avatar
+ 1
y= (x) + 3 delete the parentheses and try again!!
10th Jun 2017, 3:45 AM
Diego Moll
Diego Moll - avatar