You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

无法打印布尔值(true、false),报TypeError: must be str, not bool错误求助

Fixing TypeError: must be str, not bool in Your Python Code

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:

  1. Convert the boolean to a string explicitly
    Use str(result1) to turn the boolean into a string before concatenating:

    print(number1 + " is smaller or equal than " + number2 + ": " + str(result1))
    
  2. 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))
    
  3. 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 04:13:50