繁体   English   中英

我应该如何修复 Python 代码中的这个错误?

[英]How should I fix this mistake in my code in Python?

作为学校项目的一部分,我正在使用 python 和 csv 制作电影院预订系统。 我创建了一个 csv 文件来存储所有座位的状态,即 0=available 和 1=booked。 我已将此文件导入 python 并写出代码以允许用户选择他们希望预订的座位,如果该座位未预订(状态 = 0),则该人将能够预订它,csv 文件将更新以反映相同(状态= 1)。 出于某种原因,即使我编写了阻止我这样做的代码,我也可以预订已经预订的座位。 请有人告诉我我犯的错误吗? 我将在下面附上相关的代码段:

import csv

with open('seats.csv', newline='') as csvfile:
    seats = list(csv.reader(csvfile))


def bookSeat():
    for row in seats:
        print(row)
    print("Booking a Seat by Row/Column")
    booked = False
    while booked == False:
        row = int(input("Enter a row number (between 0 and 5) "))
        column = int(input("Enter a column number (between 0 and 7) "))

        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

            # Rewrite the CSV with the new list of seats
            writer = csv.writer(open('seats.csv', 'w', newline = ''))
            writer.writerows(seats)

如代码所示,如​​果数据库中座位的状态为 1,则应显示消息“此座位已被预订”,但由于某种原因,它会继续预订。 下面是后面用到 bookSeat 函数的地方:

if choice == "Customer":
    print("+============================+")
    print("+   CINEMA BOOKING SYSTEM    +")
    print("+============================+")
    print("")
    print("1 - Book a Seat")
    print("x - Exit")
 
    choice = input("What would you like to do? ")

    if choice=="1":
        bookSeat()
        displayBookings()
        whatNext()

    elif choice=="x":    
        print("Good Bye!")
        
    else:
        print("Invalid Menu Option")
        print("Good Bye!")

对于这种基于菜单的程序,我编写了一个菜单函数来处理大部分菜单逻辑,然后在我的多个程序中重用它。 类似于以下内容:

def menu(header, options, request):
    """
    Creates a function that will print the menu and return a valid option

    :param header: text to show at the top of the menu
    :param options: list of options to be printed
    :param request: text to show when requesting an option
    :return: function that will print the menu and return a valid option
    """
    # First, lets add the numbers to each option and prepare it to be printed
    # so that we only do this once
    digits = 0  # Maximum digits length to print them vertically aligned
    length = len(options)
    while length > 0:
        digits += 1
        length //= 10
    options_text = "\n".join([
        f"\t{i+1:{digits}d}) {option}" for i, option in enumerate(options)
    ])
    options_text += f"\n\t{0:{digits}d}) Exit"

    def print_menu():
        while True:
            print(header)
            print(options_text)

            try:
                choice = int(input(request + " "))
            except ValueError:
                print("Unable to parse input as integer.\n")
            else:
                # If the option is valid return it
                if 0 <= choice <= len(options):
                    return choice
                print("Invalid option.\n")

    return print_menu

然后你会像这样使用它:

if __name__ == '__main__':
    print_menu = menu(
        "\n".join([
            "+============================+",
            "+   CINEMA BOOKING SYSTEM    +",
            "+============================+",
        ]),
        [
            "Book a seat",
        ],
        "What would you like to do?",
    )
    while (choice := print_menu()) != 0:
        if choice == 1:
            pass  # Option 1
        elif choice == 2:
            pass  # Option 2
    print("Good bye!")

它将生成这样的菜单,将 Exit 作为最后写入的零选项:

+============================+
+   CINEMA BOOKING SYSTEM    +
+============================+
    1) Book a seat
    0) Exit
What would you like to do? 

注意:使用需要 Python 3.8+,以前你可以像这样使用它,结果完全相同:

if __name__ == '__main__':
    print_menu = menu(
        "\n".join([
            "+============================+",
            "+   CINEMA BOOKING SYSTEM    +",
            "+============================+",
        ]),
        [
            "Book a seat",
        ],
        "What would you like to do?",
    )
    choice = None
    while choice != 0:
        choice = print_menu()
        if choice == 1:
            pass  # Option 1
        elif choice == 2:
            pass  # Option 2
    print("Good bye!")

通过将此函数应用于您的代码,并进行一些额外的改进(使用字符串而不是整数来解决您的问题,枚举从 1 开始的行和列,提取读取和保存到函数,...):

import csv


def menu(header, options, request):
    pass  # Copy the code from above


def read_bookings(path):
    with open(path, 'r', newline='') as csv_file:
        return list(csv.reader(csv_file))


def save_bookings(path, bookings):
    with open(path, 'w', newline='') as csv_file:
        writer = csv.writer(csv_file)
        writer.writerows(bookings)


def display_bookings(bookings):
    for row in bookings:
        print(row)


def book_seat(bookings):
    print("Booking a Seat by Row/Column")
    while True:
        row = int(input("Enter a row number (between 1 and 6) ")) - 1
        column = int(input("Enter a column number (between 1 and 8) ")) - 1

        if bookings[row][column] == '1':
            print("This seat is already booked.")

        else:
            print("This seat is empty.")
            print("Booking seat...")

            bookings[row][column] = '1'
            # Rewrite the CSV with the new list of seats
            save_bookings('seats.csv', bookings)

            print("We have now booked this seat for you.")

            break


if __name__ == '__main__':
    print_menu = menu(
        "\n".join([
            "+============================+",
            "+   CINEMA BOOKING SYSTEM    +",
            "+============================+",
        ]),
        [
            "Book a seat",
        ],
        "What would you like to do?",
    )
    while (choice := print_menu()) != 0:
        if choice == 1:  # Book a seat
            seats = read_bookings('seats.csv')
            display_bookings(seats)
            book_seat(seats)
            display_bookings(seats)

        elif choice == 2:  # Still not implemented
            pass

    print("Good bye!")

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM