variables for python

+1 pranjal bhowal · December 29, 2015
 
its show error y????

 g = input ("Enter number here:")
Enter number here:43
>>> g + x
Traceback (most recent call last):
  File "<pyshell#6>", line 1, in <module>
    g + x
TypeError: Can't convert 'int' object to str implicitly
>>> g **3
Traceback (most recent call last):
  File "<pyshell#7>", line 1, in <module>
    g **3
TypeError: unsupported operand type(s) for ** or pow(): 'str' and 'int'
>>> g ** 9
Traceback (most recent call last):
  File "<pyshell#8>", line 1, in <module>
    g ** 9
TypeError: unsupported operand type(s) for ** or pow(): 'str' and 'int'
>>> g + 32
Traceback (most recent call last):
  File "<pyshell#9>", line 1, in <module>
    g + 32
TypeError: Can't convert 'int' object to str implicitly
>>> r = input ("enter number here:")
enter number here: 5
>>> r + 5
Traceback (most recent call last):
  File "<pyshell#11>", line 1, in <module>
    r + 5
TypeError: Can't convert 'int' object to str implicitly

Post a Reply

Replies

Oldest  Newest  Rating
0 Kartheyan Sivalingam · December 29, 2015
A beginner mistake, but not to worry, the solution is simple.

As you might now, input() is a function which allows the user to interact via the Terminal or Command Line (CMD). The input() function, is a function built into Python, which returns a string (if you don't know what functions or what I mean by return, I recommend you watch Bucky's tutorial on Functions)

Now as the function input() returns a string object, and as you should know you cannot do math operations (+, -, *, / etc) on strings. Math operations can only be done on integers and floats. So to fix your problem, you will need to cast (convert) the string returned by input to an integer, there are two ways to achieve this (which are more or less the same thing)

Another built-in function in Python is int(), this can convert an object like string to integer, allowing you to do math operations.

Solution 1:

r = int(input("Enter number here"))
r + 5

 
Solution 2:
r = input("Enter number here")
int(r) + 5


Both solutions do the same thing, the concept of objects and converting objects to different objects can be a difficult concept to get a hold of, but just carry on practicing and programming and soon enough everything will make sense; but for now just remember:

  • The input() function returns a string

  • Math operations can only be done on integers

  • To change a string object to integer, use the int() method



Good luck, I hope I helped, if you have any concerns or don't understand, don't be scared to ask :)
  • 1

Python

107,257 followers
About

This section is all about snakes! Just kidding.

Links
Moderators
Bucky Roberts Administrator