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

Python聊天机器人出现NameError: name 'leave' is not defined错误求助

解决Python聊天机器人的NameError问题

我是Python新手,写了一个简单的聊天机器人,运行时在if leave == "y":行触发了NameError: name 'leave' is not defined错误。以下是完整代码和报错信息:

原代码

import random

greetings = ["Yo,", "Hello,", "Howdy,", "Greetings,"]

print(random.choice(greetings))
print("im OCB-1")

userName = input("What is your name?")
print("Nice to meet you, " + userName + "!")
print("")

if userName == "OCB-1":
  print ("Wait, you bastar-")
  exit()
else:
  print("I hope you are having a great day!")

print("List of activites:")
print("")
print("Talk about books")
print("")
activity = input("What would you want to do?")

if activity == "Talk about books":
  print ("Sure, what book do you want to talk about? I know")
  print("Harry Potter")
  bookActivity = input(":")
else:
  print("")
  print("Unexpected Error: Activity not found (Program recognizes capital and small letters)")
  exit()
  
if bookActivity == "Harry Potter":
  print("")
  bookrateHarryPotter = input("How would you rate Harry Potter, -/10 ?")
else:
  print("")
  print("Unexpected Error: Book not found (Program recognizes capital and small letters)")
  exit()
  
  if bookrateHarryPotter(1/10, 2/10, 3/10, 4/10, 5/10, 6/10, 7/10, 8/10, 9/10, 10/10,):
    print("Nice, I think I would rate it 8/10 :).")
    print("")
    
    out = input("Do you want to go back to activites or leave?")
    out = out.lower()
  while (out != "leave"):
    
   leave = input("In this session I learned: Your Harry Potter book rate which is " + bookrateHarryPotter + ". Are you sure you want to leave? y/n")

if leave == "y":
    print("Killing session...")
    exit()
else:
  print("Unexpected Error: couldnt find y")
  print("")
  
if leave == "n":
    print("Thank you...")
    print("I will print list of Activites")
    print("List of activites:")
    print("")
    print("Talk about books")
    print("")
    activity = input("What would you want to do?")
    print("")
else:
  print("Unexpected Error: couldnt find n")
  print("")

运行报错信息

Greetings,
im OCB-1
What is your name?
Oli
Nice to meet you, Oli!

I hope you are having a great day!
List of activites:

Talk about books

What would you want to do?
Talk about books
Sure, what book do you want to talk about? I know
Harry Potter
:
Harry Potter

How would you rate Harry Potter, -/10 ?
5/10
Traceback (most recent call last):
  File "main.py", line 51, in <module>
    if leave == "y":
NameError: name 'leave' is not defined

错误原因

  • 缩进错误:判断评分的if语句缩进错误,被嵌套在else块中(而else块执行了exit(),永远不会走到这个if),导致后续的out和leave变量从未被定义,调用时触发未定义错误。
  • 错误的条件判断:if bookrateHarryPotter(1/10, ...)是错误写法——bookrateHarryPotter是用户输入的字符串,不能当作函数调用,应该检查输入是否属于合法评分列表。
  • 循环逻辑缺陷:while循环未处理out == "leave"的情况,且循环内未更新out变量,会导致无限循环。

修复方案

修复步骤

  1. 修正缩进:将判断评分的if语句调整到if bookActivity == "Harry Potter"的分支内部,确保用户输入评分后能执行后续逻辑。
  2. 替换错误判断:创建合法评分列表,用in关键字检查用户输入是否在列表内。
  3. 优化循环逻辑:调整流程,当用户选择"leave"时进入确认步骤,选择返回活动时重新显示列表,同时修复循环内的变量更新问题。

修复后的完整代码

import random

greetings = ["Yo,", "Hello,", "Howdy,", "Greetings,"]

print(random.choice(greetings))
print("im OCB-1")

userName = input("What is your name?")
print("Nice to meet you, " + userName + "!")
print("")

if userName == "OCB-1":
    print("Wait, you bastar-")
    exit()
else:
    print("I hope you are having a great day!")

# 定义显示活动列表的函数,避免重复代码
def show_activities():
    print("List of activites:")
    print("")
    print("Talk about books")
    print("")

show_activities()
activity = input("What would you want to do?")

while True:
    if activity == "Talk about books":
        print("Sure, what book do you want to talk about? I know")
        print("Harry Potter")
        bookActivity = input(":")
        
        if bookActivity == "Harry Potter":
            print("")
            valid_ratings = ["1/10", "2/10", "3/10", "4/10", "5/10", 
                            "6/10", "7/10", "8/10", "9/10", "10/10"]
            bookrateHarryPotter = input("How would you rate Harry Potter, -/10 ?")
            
            if bookrateHarryPotter in valid_ratings:
                print("Nice, I think I would rate it 8/10 :).")
                print("")
                
                while True:
                    out = input("Do you want to go back to activites or leave?").lower()
                    if out == "leave":
                        leave = input(f"In this session I learned: Your Harry Potter book rate which is {bookrateHarryPotter}. Are you sure you want to leave? y/n").lower()
                        if leave == "y":
                            print("Killing session...")
                            exit()
                        elif leave == "n":
                            print("Thank you...")
                            show_activities()
                            activity = input("What would you want to do?")
                            break
                        else:
                            print("Unexpected Error: Please enter y/n")
                            print("")
                    elif out == "go back to activites":
                        show_activities()
                        activity = input("What would you want to do?")
                        break
                    else:
                        print("Unexpected Error: Please choose 'go back to activites' or 'leave'")
                        print("")
            else:
                print("")
                print("Unexpected Error: Invalid rating (Please use format like 5/10)")
                print("")
                break
        else:
            print("")
            print("Unexpected Error: Book not found (Program recognizes capital and small letters)")
            exit()
    else:
        print("")
        print("Unexpected Error: Activity not found (Program recognizes capital and small letters)")
        show_activities()
        activity = input("What would you want to do?")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.24 11:52:49