Skip to main content
 首页 » 编程设计

python之为什么我的 "if"语句在使用 "break"函数时没有退出

2025年01月19日8lonelyxmas

这段代码就像一个售票柜台,用户可以根据价格或座位选择是否要买票。

我还没有接触到代码的座位选择部分,但是当我进行价格选择时,完成后,它会多次打印布局(而不是一个,它应该是这样)。

第一次触发“if”后,应该打印出布局,然后中断。但是,它并没有这样做,而是继续打印布局并多次通过 if 函数。

请帮我解决这个问题。谢谢!

line1 = [10 , 10 , 10 , 10 , 10 , 10 , 10 , 10 , 10 , 10] 
line2 = [10 , 10 , 10 , 10 , 10 , 10 , 10 , 10 , 10 , 10] 
line3 = [10 , 10 , 10 , 10 , 10 , 10 , 10 , 10 , 10 , 10] 
line4 = [10 , 10 , 20 , 20 , 20 , 20 , 20 , 20 , 10 , 10] 
line5 = [10 , 10 , 20 , 20 , 20 , 20 , 20 , 20 , 10 , 10] 
line6 = [10 , 10 , 20 , 20 , 20 , 20 , 20 , 20 , 10 , 10] 
line7 = [20 , 20 , 30 , 30 , 40 , 40 , 30 , 30 , 20 , 20] 
line8 = [20 , 30 , 30 , 40 , 50 , 50 , 40 , 30 , 30 , 20] 
line9 = [30 , 40 , 50 , 50 , 50 , 50 , 50 , 50 , 40 , 30] 
seats = [line1, line2 , line3 , line4 , line5 , line6 , line7 , line8 , line9] 
 
for line in seats: 
    print(line)  
 
seatFound = False 
 
SorP = input("Would you like to select a seat based on the price (P) or seat (S)") 
 
if SorP == "P": 
    price = int(input("What price would you like?")) 
    for line in seats: 
        for seat in line: 
        if seat == price: 
            print("There is a seat available for that price") 
            seatFound = True 
            position = line.index(seat) 
            line.remove(seat) 
            line.insert(position , 0) 
            for line in seats: 
                print(line)  
            break 
if seatFound != True: 
    print("There is not a seat available for this price. Try again") 

请您参考如下方法:

break 仅从最内层的 for 或 while 循环退出。代码段中的外部循环将继续执行。

for line in seats: 
    for seat in line: 
        [...] 
        # exit the inner loop. execution continues in the outer loop 
        break 

您可能希望重构您的代码,以便在一个单独的函数中执行对可用座位的搜索,该函数在找到该项目后立即执行返回。