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

Python打印根号时报类型错误:无法转换字节类型

解决Python打印时的字节类型错误

错误原因

你的代码里使用了u"\u221A".encode('utf-8'),这会生成**字节类型(bytes)**的数据。在Python 3中,print函数不能同时输出整数和字节类型的内容,混合输出就会触发类型错误。而Techsmart使用的可能是Python 2,Python 2对字节和字符串的处理逻辑不同,所以能正常运行。

修复方案

去掉.encode('utf-8'),直接使用Unicode字符串即可。Python 3默认支持Unicode字符串,直接打印"\u221A"就能正确显示根号符号。

修正后的代码

import math
square = []
perfect_squares = [1, 4, 9, 16, 25, 36, 49, 64, 81, 100, 121, 144, 169, 196, 225]
num = int(input(""))
for i in perfect_squares:
    if num % i == 0:
        square.append(i)
coefficient = max(square)
radicand = num // coefficient
coefficient = int(math.sqrt(coefficient))
if num in perfect_squares:
    print(int(math.sqrt(num)))
elif coefficient == 1:
    print("\u221A", num, sep='')
else:
    print(coefficient, "\u221A", radicand, sep='')

内容的提问来源于stack exchange,提问作者sofiatheshark

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 07:05:24