无法打印布尔值(true、false),报TypeError: must be str, not bool错误求助
Hey there! I see exactly what's causing that error in your code. Let's break it down and fix it quickly.
The Root Problem
In your final print statement:
print(number1 + "is smaller or equal than" + number2 + ":" + result1)
The variable result1 holds a boolean value (True or False) from this line:
result1 = number1 <= number2
Python doesn't let you directly concatenate strings with boolean values using the + operator—that's why you're getting the TypeError: must be str, not bool message.
Easy Solutions
You have a few simple ways to fix this:
Convert the boolean to a string explicitly
Usestr(result1)to turn the boolean into a string before concatenating:print(number1 + " is smaller or equal than " + number2 + ": " + str(result1))Use string formatting (like you did for the average)
This is cleaner and automatically handles type conversion for you:print("{} is smaller or equal than {}: {}".format(number1, number2, result1))Use f-strings (Python 3.6+)
F-strings are the most readable option for modern Python:print(f"{number1} is smaller or equal than {number2}: {result1}")
Full Corrected Code
Here's your code with the f-string fix applied (plus a couple of small tweaks for accuracy and readability):
number1 = input("Hello, tell me one number! :") number2 = input("Now the second number! :") sum_avg = (float(number1) + float(number2))/2 # Renamed 'sum' to avoid overwriting the built-in function result1 = float(number1) <= float(number2) # Compare numeric values, not raw strings print("Number 1 is:" + number1 ) print("Number 2 is:" + number2 ) print("The average of {0} and {1} is {2}".format(number1, number2, sum_avg)) print(f"{number1} is smaller or equal than {number2}: {result1}")
Note: I adjusted result1 to compare the float versions of your inputs—if you compare raw strings like "10" and "2", Python will check character order instead of numeric value, giving you an incorrect False result.
内容的提问来源于stack exchange,提问作者Sinisa

