【问题标题】:Trying to deduct values from original values试图从原始值中减去值
【发布时间】:2023-04-04 22:37:02
【问题描述】:

所以我在下面写了一个小程序。它工作得很好,除了我似乎无法让它工作的一部分。每次购买/订购一个或多个时,我都会尝试从 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)

【问题讨论】:

  • “你能检查我的代码并帮助我改进吗?”如果您能查明导致意外结果的线路,我们将真的感激不尽。在每个阶段,尝试使用print 语句来查看发生了什么。否则,我担心这个问题可能过于宽泛而无法回答。
  • 当前输出是多少?期望的输出是什么?

标签: python loops auto-increment


【解决方案1】:

看起来这是一个较大应用程序的一部分的方法。如果是这种情况,general_seats 可能不应该每次都重置为 10。相反,开放席位的数量(我认为genetal_seats)应该作为变量传递,以便可以更改然后返回。根据其他因素,它可以设置为全局变量,但这通常不是最佳实践。我希望这就是你要找的。如果我误解了,请告诉我。

澄清后编辑:如果将它们设置为全局变量,则可以从函数中删除 general_seats = 10floor_seats = 4。每次函数运行时,这两行将变量分别重置为 10 和 4。

【讨论】:

  • 是的,这就是我想问的。我尝试将它们设置为全局,但它们(general_seats 和 floor_seats)每次都重置为 10。
  • 是的,general_seats = 10 和 floor_seats = 4 是重置值的行。如果将它们设置为全局,则这两行可以一起删除。
【解决方案2】:

每次调用 ticket_check 时,都会创建一个值为 10 的新 general_seats 变量。您需要将变量移到函数调用之外,以便在调用之间保持不变。

【讨论】:

  • 我尝试将它们设置为全局,但它们(general_seats 和 floor_seats)每次都重置为 10。
  • 你是在循环调用ticket_check函数吗?你能在你的问题中添加一些周围的代码(以及你对全局变量的修改)吗?
  • 非常感谢!我刚刚尝试使用循环,它起作用了。
猜你喜欢
  • 2021-04-21
  • 2015-06-26
  • 2013-12-21
  • 2017-12-12
  • 2021-11-07
  • 2010-11-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多