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

Python航空预订系统while循环输入判断异常问题求助

解决航空预订系统的分支逻辑问题

嘿,我看到你遇到的这个小bug啦!这其实是Python新手很容易踩的一个逻辑陷阱,咱们来一步步把它搞定~

问题根源:错误的条件判断

你代码里的这个判断语句是核心问题:

if seat_answer == 'yes' or 'Yes':

在Python中,or运算符两边是独立的布尔表达式,这句话等价于:

if (seat_answer == 'yes') or ('Yes'):

而Python里非空字符串会被判定为True,所以不管seat_answer是什么值,'Yes'本身永远是真,这个条件会一直成立,自然永远只会执行第一个分支的输出。

修复方案

这里有几种更靠谱的写法:

方案1:统一转为小写判断(推荐,兼容性更强)

把用户输入转为小写,这样不管输入Yes/YES/yEs都能匹配:

if seat_answer.lower() == 'yes':

方案2:用in判断是否在指定列表中

如果只想匹配严格的yes或Yes,可以这么写:

if seat_answer in ['yes', 'Yes']:

额外的优化建议

除了这个核心问题,你的代码还有几个可以完善的地方:

  • 你的while True循环里最后直接写了break,导致循环只会执行一次,失去了循环的意义,如果想让用户输入错误时重新询问,需要调整break的位置;
  • 当用户输入no询问是否重新开始时,没有后续的处理逻辑,可以补充对应的分支代码;
  • 类airline_reservations目前还没被用到,可以考虑把座位相关的逻辑整合到类里,让代码更结构化。

修改后的示例代码

class AirlineReservations():  # Python类名建议采用大驼峰命名法
    def __init__(self, type_of_seat, no_of_seats):
        self.type_of_seat = type_of_seat
        self.no_of_seats = no_of_seats

def check_availability(no_of_seats):
    first = 14
    business = 76
    economy = 399
    total_seats = first + business + economy
    remaining_seats = total_seats - no_of_seats
    
    if no_of_seats <= remaining_seats:
        while True:  # 循环处理用户输入,直到得到有效回应
            seat_answer = input("Seats are available. Would you like to confirm? ")
            if seat_answer.lower() == 'yes':
                print("You have chosen your seats. Thank you.")
                break  # 完成操作后退出循环
            elif seat_answer.lower() == 'no':
                seat_answer2 = input("Would you like to start over? ")
                # 这里可以补充重新开始或退出的逻辑,比如:
                if seat_answer2.lower() == 'yes':
                    print("Restarting the reservation process...")
                    break
                else:
                    print("Thank you for using our service.")
                    break
            else:
                print("We cannot recognize this input, please try again.")
    else:
        print("Sorry, not enough seats available.")

# 测试调用
check_availability(2)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.06 22:52:39