所以我在下面写了一个小程序。它运作良好,除了我似乎无法使其工作的一部分。每次拍摄/订购一件或多件时,我试图从原始值10或4中扣除开放座位。但我看不到能够做到这一点。除此之外,我的代码似乎对我有用。你能查看我的代码并帮助我改进吗?感谢。
例如,每次用户输入需要的座位数时,都会想要扣除一般座位中的座位数。如果他们需要2个座位,那么它应该是10到2个,或者如果他们需要地板座位,它应该是4 - 2
def ticket_check(section, seats):
sections = "general \n floor"
general_seats = 10
floor_seats = 4
total_seats = general_seats + floor_seats
print ("Available sections:",sections)
section = input("Chose a section (G or F): ").capitalize()
if general_seats > 0 or floor_seats > 0:
if section == "G":
print ("Available seats", general_seats)
if general_seats > 0:
general_seat_order = int(input("Choose no. of seats: "))
general_seats = general_seats - general_seat_order
print ("Your seat order has been confirmed")
else:
print ("Sorry, no more general seats available")
elif section == "F":
print ("Available seats",floor_seats)
if floor_seats > 0:
floor_seat_order = int(input("Choose no. of seats: "))
floor_seats = floor_seats - floor_seat_order
print ("Your seat order has been confirmed")
else:
print ("Sorry, No more floor seats available")
else:
print ("Sorry, Section not available")
else:
print ("Pre-sale seats are sold out")
ticket_check("general \n floor", 14)
答案 0 :(得分:1)
每次调用ticket_check
时,都会创建一个值为10的新general_seats
变量。您需要在函数调用之外移动变量,以使其在调用之间保持不变。
答案 1 :(得分:0)
看起来这是一个更大的应用程序的一部分的方法。如果是这种情况,general_seats
每次可能不应重置为10。相反,开放席位的数量(我认为genetal_seats
)应作为变量传递,以便可以更改然后返回。根据其他因素,可以将其设置为全局变量,但这通常不是最佳实践。我希望这就是你要找的东西。如果我误解了,请告诉我。
澄清后编辑:如果将它们设置为全局变量,则可以从函数中删除general_seats = 10
和floor_seats = 4
。每次函数运行时,这两行都会将变量重置为10和4。