作为学校项目的一部分,我正在使用python和csv制作电影院预订系统。我创建了一个存储所有席位状态的csv文件,即0 =可用,1 =预订。我已将此文件导入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!")
答案 0 :(得分:0)
对于这种基于菜单的程序,我编写了一个菜单函数来处理大多数菜单逻辑,然后在我的多个程序中重用它。类似于以下内容:
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!")