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

如何从Yes/No函数获取返回值并用于后续代码逻辑判断

解决方案

1. 重构yesNo()函数,让它返回用户的选择

把原函数里直接执行tutorial()/startGame()的逻辑移除,改为返回代表用户选择的布尔值,让函数只专注于获取有效输入这一件事:

prompt = " >>> "

def yesNo():
    while True:
        # 对输入做小写转换+去空格处理,避免空格或大小写导致判断失误
        answer = input('(Y/N)' + prompt).strip().lower()
        if answer == 'y':
            return True  # 返回True表示用户想要教程
        elif answer == 'n':
            return False  # 返回False表示跳过教程
        else:
            print("command not understood. try again.")

2. 在newGame()中获取返回值并判断逻辑

调用yesNo()拿到用户的选择后,再决定是否运行tutorial():

def newGame():
    print("would you like a tutorial?")
    wants_tutorial = yesNo()
    if wants_tutorial:
        tutorial()
    else:
        startGame()

改动说明

  • 移除了原代码中冗余的i计数变量,用while True循环更简洁直观
  • 对用户输入做了strip()处理,避免用户误输入空格导致判断失败
  • 函数职责分离:yesNo()只负责收集有效输入,newGame()负责业务逻辑判断,代码更易维护和扩展

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.24 23:48:14