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

标签 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")

最佳答案

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

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

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

关于python - 为什么我的 "if"语句在使用 "break"函数时没有退出?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50092815/

相关文章:

python - 可变长度 'yield' ?

python - 如何在Python中仅丢弃html标签并提取关联文本

java - 从 Java 内部处理 Python IO

c++ - 如何离开循环

performance - 计算矩阵值包括 0 的频率

C++ for 循环字符串比较逻辑存在缺陷

Java - 访问for循环内外的变量

python - 新的 Dataframe 列作为其他行的通用函数(spark)

php - 页面刷新和数据库检查后值+1

javascript - 通过将鼠标悬停在数组 jquery 上进行迭代