如何在while循环内正确使用条件?Cottage可用性查询循环异常排查
问题解决:小屋编号检查时同时输出1和2的问题
问题描述
我写了一段代码,用来检查输入的小屋编号是否存在数据库中,如果不符合要求就循环让用户重新输入。但在while循环里,当输入的编号存在时,不该触发的else语句却执行了,导致同时输出1和2;当编号不存在时只输出2,这符合预期,但我希望编号存在时不要触发else语句。
原代码:
cottageNotAvailable = False mycursor.execute("SELECT * FROM reserved") occupide = 0 name = input("Enter Name: ") cottage_row = int(input("Select Cottage Row: ")) while cottage_row < 1 or cottage_row > 2: cottage_row = int(input("Select Cottage Row: ")) cottage = int(input("Select Cottage: ")) ##ROW 1 Cottages if cottage_row == 1: subtotals = 1000 ##Check Cottage if available users = mycursor.fetchall() for allUser in users: if str(cottage) in str(allUser[3]): cottageNotAvailable = True while cottage < 1 or cottage > 5 or cottageNotAvailable: print("======Cottage is not available=======") cottage = int(input("Select Cottage: ")) for allUser2 in users: if(str(cottage) in str(allUser2[3])): print("1") else: print('2')
问题原因
核心问题出在遍历数据库记录的循环里:你遍历了users中的每一条记录,只要某条记录的小屋编号不匹配,就会执行else分支输出2。哪怕有一条记录匹配输出了1,其他不匹配的记录依然会触发else,所以会同时看到1和2的输出。
另外原代码还有一个语法错误:while cottage_row <1 or cottage_row>2下面的cottage_row = ...语句没有缩进,这会导致代码无法正常执行。
修正方案
调整逻辑:先遍历所有记录检查是否存在匹配项,用标志位记录结果,遍历完成后再根据标志位输出内容,而不是边遍历边输出。同时修复缩进问题,找到匹配项后立即跳出循环减少无效遍历。
修正后的代码:
cottageNotAvailable = False mycursor.execute("SELECT * FROM reserved") name = input("Enter Name: ") cottage_row = int(input("Select Cottage Row: ")) # 修复缩进:循环体需要缩进 while cottage_row < 1 or cottage_row > 2: cottage_row = int(input("Select Cottage Row: ")) cottage = int(input("Select Cottage: ")) # ROW 1 Cottages if cottage_row == 1: subtotals = 1000 # Check Cottage if available users = mycursor.fetchall() # 初始检查小屋是否被占用 for allUser in users: if str(cottage) in str(allUser[3]): cottageNotAvailable = True break # 找到匹配项后立即跳出循环,无需继续遍历 while cottage < 1 or cottage > 5 or cottageNotAvailable: print("======Cottage is not available=======") cottage = int(input("Select Cottage: ")) # 每次输入新编号后,重置标志位重新检查 cottageNotAvailable = False for allUser2 in users: if str(cottage) in str(allUser2[3]): cottageNotAvailable = True break # 找到匹配就停止遍历 # 根据最终检查结果输出 if cottageNotAvailable: print("1") else: print("2")
关键修改点
- 修复缩进错误:给
while cottage_row <1...的循环体加上缩进,保证语法正确。 - 优化遍历逻辑:找到匹配的记录后立即用
break跳出循环,避免不必要的遍历。 - 统一输出时机:将输出逻辑移到遍历完成后,根据最终的
cottageNotAvailable标志位结果输出,不会出现同时输出1和2的情况。 - 重置标志位:每次输入新的小屋编号后,先重置
cottageNotAvailable为False,再重新检查,避免之前的结果影响新的判断。
内容的提问来源于stack exchange,提问作者Christopher
相关产品推荐
相关产品推荐

