Skip to main content
 首页 » 编程设计

python之为什么在 logging.info 中显示名称错误

2025年05月04日17飞鱼

我收到以下代码的错误:

logging.info("Hypotenuse of {a}, {b} is {c}".format(a=3, b=4, c=hypotenuse(a,b))) NameError: name 'a' is not defined


import logging 
logging.basicConfig(level=logging.INFO) 
 
def hypotenuse(a, b): 
    """Compute the hypotenuse""" 
    return (a**2 + b**2)**0.5 
 
logging.info("Hypotenuse of {a}, {b} is {c}".format(a=3, b=4, c=hypotenuse(a,b))) 

期望输出

INFO:root:Hypotenuse of 3, 4 is 5.0 

请您参考如下方法:

我很确定它唯一可行的方法是在调用之前定义变量:

a,b = (3,4) 
logging.info("Hypotenuse of {a}, {b} is {c}".format(a=a, b=b, c=hypotenuse(a,b)) 

可能更清楚一点:

a,b = (3,4) 
logging.info("Hypotenuse of {}, {} is {}".format(a, b, hypotenuse(a,b))