Total Pageviews

2016/03/06

[Python] TypeError: Can't convert 'int' object to str implicitly

Problem
I have a Python program as bellows:
1
2
3
4
5
def checkNum(num):
    if(num>0):
        print("* number > 0 ( you input " + num + " ).")
    else:
        print("* num < 0 ( you input " +  num + " ).")

As I try to do test, it showed error message as following:
1
2
3
4
5
6
7
8
>>> import myUtil
>>> myUtil.checkNum(10)
Traceback (most recent call last):
  File "<pyshell#3>", line 1, in <module>
    myUtil.checkNum(10)
  File "C:\Users\albert\AppData\Local\Programs\Python\Python35-32\lib\site-packages\myUtil.py", line 3, in checkNum
    print('* number > 0 ( you input ' + num +' )')
TypeError: Can't convert 'int' object to str implicitly


How To
You need to use str function to convert number to String
1
2
3
4
5
def checkNum(num):
    if(num>0):
        print("* number > 0 ( you input " + str(num) + " ).")
    else:
        print("* num < 0 ( you input " +  str(num) + " ).")

Test result:
1
2
3
4
5
6
>>> import myUtil
>>> myUtil.checkNum(89)
* number > 0 ( you input 89 ).
>>> myUtil.checkNum(-20)
* num < 0 ( you input -20 ).
>>> 


Reference
[1] http://stackoverflow.com/questions/13654168/typeerror-cant-convert-int-object-to-str-implicitly

No comments: