Skip to content
Advertisement

Having a problem in python: Showing error can only concatenate str (not “bool”) to str

I am quite new to python, so sorry for the “noob” code if you will say. But please help me : I am trying to add two numbers and show which one is bigger as a boolean value

num_1 = input("Enter first number: ")    
num_2 = input("Enter second number: ")

num_1 = int(num_1)
num_2 = int(num_2)

Sum = num_1 + num_2

print(Sum)

Greater = num_1 > num_2
Smaller = num_1 < num_2

print("is number 1 greater than number 2?  " + Greater)
print("is number 2 greater than number 1?  " + Smaller)

Advertisement

Answer

The result of a comparison operator is a boolean (either True or False). As the error message says, you can’t concatenate strings with boolean values, as Python is a strongly typed language. You have several options:

  1. Pass them as separate arguments to the print function:

    print("is number 1 greater than number 2?", Greater)
    print("is number 2 greater than number 1?", Smaller)
    
  2. Use an f-string:

    print(f"is number 1 greater than number 2? {Greater}")
    print(f"is number 2 greater than number 1? {Smaller}")
    
  3. Use .format():

    print("is number 1 greater than number 2? {}".format(Greater))
    print("is number 2 greater than number 1? {}".format(Smaller))
    
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement