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

在函数内嵌套else语句调用函数时触发NameError问题

问题分析与修复

核心问题

  1. 方法调用错误:代码中choice.lower是引用方法对象而非调用方法,必须写成choice.lower();同时比较的字符串要和lower()转换后的小写一致,应该用"y"而非"Y"。
  2. 逻辑错误:第一次选择N后,询问确认时没有重新获取用户输入,仍使用第一次的choice变量,导致逻辑完全偏离预期。
  3. 作用域问题:如果之前调用dartmoor_inn()正常,那么当前报错是因为dartmoor_inn()的定义在Baker_Street()之后,或者被放在了局部作用域中,导致Baker_Street()无法访问该函数。

修复后的代码

import time as t
from os import system, name

def clear():
    # 跨平台清屏函数
    if name == 'nt':
        _ = system('cls')
    else:
        _ = system('clear')

def type(text):
    # 打字机效果模拟函数
    for char in text:
        print(char, end='', flush=True)
        t.sleep(0.05)

# 确保dartmoor_inn定义在调用它的函数之前
def dartmoor_inn():
    print("Welcome to Dartmoor Inn!")

def Baker_Street():
    print("""
        A man named Henry Knight comes to visit you and Watson, to understand something that has plagued him   
        his whole life. 
        Henry witnessed his father's death by a gigantic hound at Dartmoor 20 years ago.
        After years of therapy Henry finally visited the site of the incident again, 
        and to his shock and surprise sees the hound again, which prompts his request for help.
        """, end='')
    t.sleep(5)
    clear()
    type("\nDo you agree to help Mr.Knight and solve this mystery? Y/N")
    choice = input(">>> ").strip()
    
    if choice.lower() == "y":                                                 
        dartmoor_inn()
    else:
        type("\nAre you sure? Y/N")
        # 重新获取确认输入,不再复用之前的choice
        confirm_choice = input(">>> ").strip()
        if confirm_choice.lower() == "y":
            exit()
        else:
            print('Great Choice! Onto Dartmoor Inn.')
            dartmoor_inn()

Baker_Street()

关键修复说明

  • 修正字符串方法调用:使用choice.lower()替代choice.lower,并匹配小写的"y",解决大小写输入不兼容问题。
  • 新增确认输入变量:在二次询问时用confirm_choice接收用户输入,修复逻辑复用旧变量的错误。
  • 调整函数定义顺序:将dartmoor_inn()放在Baker_Street()之前,确保全局作用域下可被正常调用。
  • 添加.strip()处理输入:去除用户输入前后的空格,避免因意外空格导致匹配失败。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 22:35:56