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

Python中if/else/elif的正确用法及新手程序bug修复求助

问题修复方案

你的问题根源是没有用条件分支控制后续代码——不管你第一个输入是Yes还是No,询问Phi的语句都会被执行,所以才会出现输入No后仍被提问的情况。

正确代码示例

# 获取用户的第一个回答
first_response = input("Are you willing to take the question? ")

# 根据回答执行对应逻辑
if first_response == 'Yes':
    # 只有输入Yes时才会执行这行提问
    phi_question = input("What is the value of Phi? ")
    # 这里可以添加对Phi答案的判断逻辑,比如:
    # if phi_question == "1.618":
    #     print("Correct!")
    # else:
    #     print("Wrong answer.")
elif first_response == 'No':
    print("Have a good day")
else:
    # 处理非Yes/No的输入,让程序更健壮
    print("请输入Yes或No哦")

关键说明

  • 把第一个输入的结果存在变量first_response里,用if-elif-else做分支判断
  • 询问Phi的代码被包裹在if first_response == 'Yes'的块里,只有满足条件才会执行
  • 新增的else分支可以处理用户输入其他内容的情况,避免程序无响应

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.25 15:39:36