Python TypeError: can only concatenate str (not “int”) to str

 code

def gcd(x, y):
    (x, y) = (y, x) if x > y else (x, y)
    for factor in range(x, 0, -1):
        if x % factor == 0 and y % factor == 0:
            return factor


if __name__ == '__main__':
    num1 = int(input("Please enter a positive integer: "))
    num2 = int(input("Please enter a positive integer. "))
    print("i" + gcd(num1, num2))

code error

PS G:\vscode_worksapce\vscode_python_workspace> python -u "g:\vscode_worksapce\vscode_python_workspace\test1.py"      
Please enter a positive integer: 3
Please enter a positive integer: 9
Traceback (most recent call last):
  File "g:\vscode_worksapce\vscode_python_workspace\test1.py", line 11, in <module>
    print("i" + gcd(num1, num2))
TypeError: can only concatenate str (not "int") to str

causes and solutions

reference the blog https://blog.csdn.net/feng2147685/article/details/86494905, and https://www.cnblogs.com/Jimc/p/9606112.html

is a Python string concatenation problem;

if __name__ == '__main__':
    num1 = int(input("Please enter a positive integer: "))
    num2 = int(input("Please enter a positive integer. "))
    print("i%d" % (gcd(num1, num2)) + "hahahha")

HMM…

Similar Posts: