Python基于CSV的影院订座系统可重复预订已占座位的问题排查
核心根因
导致已订座位拦截失效的关键错误是CSV读取值的类型不匹配
csv.reader解析文件时,会将所有单元格内容读取为字符串类型:哪怕CSV文件里存的是数字0、1,读入到Python的seats列表后,实际存储的是"0"、"1"格式的字符串,而非整数类型。- 原有代码中的判断语句
if seats[row][column] == 1,是拿字符串值和整数1做等值比较,在Python中不同类型的值永远无法相等,因此这个判断的结果永远为False。 - 无论目标座位的实际状态是已订(值为字符串"1")还是可用(值为字符串"0"),代码都会跳过已订拦截的分支,直接进入else的预订流程,造成可以反复预订已占座位的现象。
附带的潜在问题
- 写入CSV文件时没有使用上下文管理器,直接调用
open()返回的文件对象没有手动关闭,极端场景下会出现文件写入中断、数据未正常落盘、句柄泄漏的问题。 - 缺少用户输入的合法性校验:用户输入非整数、输入的行列号超出实际座位范围时,会直接触发程序崩溃,没有友好的错误提示。
修复实现
- 解决类型不匹配问题,两种可选方案
- 方案一:在判断已订状态时,将比较值改为字符串形式:把判断逻辑替换为
if seats[row][column] == "1",即可实现正常拦截。 - 方案二:读取CSV时就将所有单元格值转为整数,后续所有读写、判断逻辑都基于整数操作,更符合业务语义,避免同类类型错误。
- 方案一:在判断已订状态时,将比较值改为字符串形式:把判断逻辑替换为
- 所有文件读写操作统一使用
with上下文管理器,自动处理文件关闭逻辑。 - 补充输入合法性校验,覆盖非整数输入、越界输入的场景,给出明确提示。
修复后的核心参考代码:
import csv # 读取CSV时直接将单元格值转为整数,从根源解决类型不匹配问题 with open('seats.csv', newline='') as csvfile: seats = [[int(cell) for cell in row] for row in csv.reader(csvfile)] def bookSeat(): total_rows = len(seats) total_cols = len(seats[0]) if total_rows > 0 else 0 print("Booking a Seat by Row/Column") booked = False while booked is False: # 输入合法性校验 try: row = int(input(f"Enter a row number (between 0 and {total_rows - 1}) ")) column = int(input(f"Enter a column number (between 0 and {total_cols - 1}) ")) # 越界判断 if not (0 <= row < total_rows and 0 <= column < total_cols): print(f"Input out of valid range! Row range: 0-{total_rows-1}, Column range: 0-{total_cols-1}") continue except ValueError: print("Please input a valid integer for row/column!") continue # 整数与整数比较,可正常识别已订座位 if seats[row][column] == 1: print("This seat is already booked.") else: print("This seat is empty.") print("Booking seat...") seats[row][column] = 1 print("We have now booked this seat for you.") booked = True # 用with语句安全写入CSV with open('seats.csv', 'w', newline='') as csvfile: writer = csv.writer(csvfile) writer.writerows(seats)
内容的提问来源于stack exchange,提问作者Shreenath
相关产品推荐
相关产品推荐

