当我使用“break”函数时,为什么我的“if”语句没有退出?

时间:2018-04-30 01:11:32

标签: python loops for-loop if-statement break

此代码类似于票箱计数器,用户可根据价格或座位选择是否需要票证。

我没有得到代码的座位选择部分,但是当我选择一个价格时,它完成后会打印出布局太多次(而不是一次,应该如何)。

第一次触发“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")

1 个答案:

答案 0 :(得分:1)

break仅从最里面的forwhile循环退出。您的代码段中的外部循环将继续执行。

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

您可能需要重构代码,以便在找到项目后立即执行return的单独功能中搜索可用席位。

相关问题