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

封装场景下条件分支失效:仅调用timid_person方法问题排查

问题原因与修复方案

核心问题:逻辑判断的语法错误

你的代码里的条件判断写法完全错误:

  • 原代码的if "sorry" or "please" in scene: 等价于 if (True) or ("please" in scene),因为非空字符串"sorry"在布尔语境下永远是True,所以不管输入什么内容,这个条件都会成立,自然永远执行timid_person方法。
  • 同理,elif "beat" or "break" in scene: 也是同样的错误写法,"beat"本身是True,不过因为第一个条件永远成立,这个分支根本不会被触发。

正确的条件判断应该是每个关键词都要单独判断是否在输入字符串里,比如:if "sorry" in scene or "please" in scene:

次要问题:多余的print调用

你的Character类里的三个方法已经用print输出内容了,但调用时又写了print(act1.timid_person()),这会导致方法执行后额外输出一个None(因为方法没有返回值,默认返回None),所以直接调用方法即可,不需要外层的print。

修复后的完整代码

import random
class Character:

    def __init__(self):
        stuff = ["lunch", "bag", "money", "phone"]
        self.__obj = random.choice(stuff)

    def timid_person(self):
        print('im sorry could you please return my ' + self.__obj)

    def bully_person(self):
        print('give me that ' + self.__obj + ' or ill break your head')

    def nice_person(self):
        print('you cant have my ' + self.__obj)

act1 = Character()
scene = input("someone is trying to rob you what is your response:")
if "sorry" in scene or "please" in scene:
    act1.timid_person()
elif "beat" in scene or "break" in scene:
    act1.bully_person()
else:
    act1.nice_person()

另外,我给字符串拼接处加了空格,让输出的句子更通顺,避免出现give me thatbagor ill...这种连在一起的错误格式。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.12 21:18:10