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

为何提示‘name is not defined’?Python写入Excel新行报错咨询

问题分析与解决

错误根源

  • 变量作用域问题:Name、Age等变量在New()函数内部定义,属于局部变量,函数外部无法直接访问。执行data = [(Name,Age,Height,DOB)]时,Python找不到这些变量的定义,因此抛出Name is not defined错误。
  • 额外问题:
    • exit是内置函数,需加括号调用exit(),否则仅引用函数不会终止程序;
    • Windows路径中的\是转义字符,直接使用会导致路径解析错误;
    • 代码中存在拼写错误:celebirty应为celebrity。

修正方案

方案一:通过函数返回值传递数据

将用户输入的信息作为函数返回值,外部接收后再写入Excel:

import openpyxl

# 使用原始字符串处理Windows路径,避免转义问题
wb = openpyxl.load_workbook(r"H:\Grade10\Cs\Mir Hussain 12.04.00.xlsx")
sheet = wb.active

def New():
    choice = input("Would you like to add a new row? ")
    if choice == 'Yes':
        Name = input("What is the name of that celebrity? ")
        Age = input("What is the age of the celebrity? ")
        Height = input('What is the height of the celebrity? ')
        DOB = input('What is the Date of birth of the celebrity? ')
        return (Name, Age, Height, DOB)
    elif choice == 'No':
        exit()  # 正确调用退出函数

# 接收函数返回的用户输入
user_data = New()
if user_data:
    sheet.append(user_data)
    wb.save(r"H:\Grade10\Cs\Mir Hussain 12.04.00.xlsx")

方案二:将写入逻辑封装到函数内部

把Excel写入操作放到New()函数里,避免跨作用域访问变量:

import openpyxl

wb = openpyxl.load_workbook(r"H:\Grade10\Cs\Mir Hussain 12.04.00.xlsx")
sheet = wb.active

def New():
    choice = input("Would you like to add a new row? ")
    if choice == 'Yes':
        Name = input("What is the name of that celebrity? ")
        Age = input("What is the age of the celebrity? ")
        Height = input('What is the height of the celebrity? ')
        DOB = input('What is the Date of birth of the celebrity? ')
        # 直接在函数内写入数据
        sheet.append((Name, Age, Height, DOB))
        wb.save(r"H:\Grade10\Cs\Mir Hussain 12.04.00.xlsx")
    elif choice == 'No':
        exit()

New()

关键注意点

  • 优先通过函数返回值传递局部变量,避免使用global声明全局变量(易引发代码混乱);
  • Windows路径建议用原始字符串(前缀r)或双反斜杠\\处理,防止转义字符干扰;
  • 内置函数需加括号调用,比如exit(),否则无法执行对应操作。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 09:35:35