[英]What should i do to fix the NoSuchElementException error in my python code?
[英]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.