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

Python中如何让变量在if语句内正常工作?

问题分析与解决方案

你的代码存在两个核心问题,导致变量和条件判断无法正常工作:

1. 条件判断逻辑错误

你写的if arrived == 'yes' or 'Yes'是无效写法,Python会将其解析为(arrived == 'yes') or 'Yes'。由于非空字符串'Yes'在布尔判断中永远为True,这个条件会一直成立,不管输入什么内容都会执行第一个分支的代码。

正确的写法有两种:

  • 统一将输入转为小写(或大写)后判断,兼容各种大小写输入:
    if arrived.lower() == 'yes':
    
  • 直接判断输入是否在指定列表中:
    if arrived in ['yes', 'Yes']:
    

同理,后续的elif arrived == 'no' or 'No'也需要做同样修改。

2. 变量doorbell未初始化导致报错

当你第一个问题回答'no'或其他内容时,doorbell变量根本不会被定义,此时执行后面的if doorbell == ...语句会直接抛出NameError。

解决思路有两种:

  • 提前初始化doorbell变量,比如在代码开头添加doorbell = '';
  • 把第二个判断逻辑放到第一个if arrived.lower() == 'yes'的分支内部,仅当第一个条件满足时才执行第二个判断,避免变量未定义的情况。

修正后的完整代码

arrived = input('Have the doorbell ringed?: ')

if arrived.lower() == 'yes':
    doorbell = input('Is it from ifood?: ')
    if doorbell.lower() == 'yes':
        print('Your ifood have arrived!!!')
    elif doorbell.lower() == 'no':
        print('It is not your ifood yet, keep waiting')
    else:
        print('Please answer the questions with yes or no')
elif arrived.lower() == 'no':
    print('It is not here yet, keep waiting')
else:
    print('Please answer the first question with yes or no')

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.20 09:02:08