print_output函数NameError及代码格式问题排查咨询
代码错误排查与修复
核心问题:NameError: name 'print_output' is not defined
这个错误出现的根本原因是你的代码存在语法错误,导致Python解释器无法完整解析整个脚本——即便print_output函数写在最前面,后续函数的语法错误会让解释器中途停止解析,最终print_output没有被成功注册到运行环境中。
触发语法错误的具体代码
triangle_hypotenuse函数的赋值逻辑颠倒:
你写了sqrt((side_1 ** 2) + (side_2 ** 2)) = h,这完全不符合Python的赋值规则——必须是变量在左、表达式在右,正确写法是h = sqrt((side_1 ** 2) + (side_2 ** 2))。另外,sqrt函数属于math模块,你没导入就直接用了,会引发另一个错误。
其他隐藏错误
除了导致NameError的语法问题,代码里还有这些问题:
polar_coords函数未导入math模块:
这个函数里用了math.sqrt、math.atan和math.pi,但代码开头没有写import math,运行时会报错。dollars_to_euros函数格式化错了变量:
你计算出euros = dollars * 0.99,但格式化时却用了dollars变量,应该改成"{:.2f}".format(euros),不然输出的还是美元数值。polar_coords存在除以0风险:
当x=0时,y/x会触发除以0错误,建议加个判断处理这种情况。
修复后的完整代码
import math from math import sqrt def print_output(i): print(f"OUTPUT {i}") def triangle_hypotenuse(side_1, side_2): h = sqrt((side_1 ** 2) + (side_2 ** 2)) h = "{:.2f}".format(h) print_output(h) def feet_to_meters(feet): meters = feet / 3.281 meters = "{:.4f}".format(meters) print_output(meters) def polar_coords(x, y): radius = math.sqrt(x * x + y * y) # 处理x为0的情况,避免除以0报错 if x == 0: theta = 90 if y > 0 else 270 else: theta = math.atan(y / x) theta = 180 * theta / math.pi r = "{:.2f}".format(radius) t = "{:.2f}".format(theta) phrase_1 = "r: " + r + " " # 加个空格让输出更清晰 phrase_2 = "theta: " + t combined = phrase_1 + phrase_2 print_output(combined) def dollars_to_euros(dollars): euros = dollars * 0.99 euros = "{:.2f}".format(euros) print_output(euros)
将修复后的代码完整运行后,再调用print_output("Hello World")就能正常输出OUTPUT Hello World了。
内容的提问来源于stack exchange,提问作者Sailekha Sivasamy
相关产品推荐
相关产品推荐

