【问题标题】:Recurring line disappearance, issue with while loop重复行消失,while循环问题
【发布时间】:2019-07-23 01:54:47
【问题描述】:

*我是python新手,所以要温柔...

总体问题:我最近编写的多个代码存在问题,其中行被跳过,这显然是我的错误。我知道我一定是搞砸了一些东西,但我只是没有看到它。我最近的一期可以在这里找到:Is there any reason Python would skip a line?

现在,我想编写一个预售有限数量门票的应用程序。以下是条件:

“每个买家最多可以购买4张门票。共有15张门票可供预售。程序应提示用户他们要购买的门票数量,然后显示数量剩余门票。重复直到所有门票都售完,然后显示买家总数。"

正在发生类似的问题。

buy = int()
ticket_num = 15
buyers = 0

while ticket_num > 0:
    buy = int(input("How many tickets would you like to purchase? "))
    if buy > 4:
        print("You cannot buy that many (4 max).")
        buy = input("How many tickets would you like to purchase? ")
    else:
        ticket_num = ticket_num - buy
        print("There are currently", ticket_num, "remaining.")
        buyers = buyers + 1

print() 

print("The total number of buyers was:", buyers)

似乎没有读取“else”结构中的打印行,我不太明白为什么......

谁能帮我了解一下我的总体误解是什么......?

【问题讨论】:

    标签: python if-statement while-loop


    【解决方案1】:

    我想通了。我对这个问题有一些不正确的地方:

    • 我没有足够的条件语句 (elif) 来满足要求
    • 我不需要在 if 语句中让 buy 变量再次收集输入,因为 while 循环已经导致程序再次提示输入。
    • 我根本不需要将 buy 变量放在 while 循环之外,我只需在“if”语句中使用它之前对其进行初始化。

    解决方法如下:

    tickets = 15
    buyers = 0
    print("There are currently", tickets, "tickets available.")
    
    while tickets > 0 :
        buy = int(input("How many tickets would you like to purchase? "))
        if buy <= 4 and tickets - buy >= 0:
            tickets = tickets - buy
            buyers = buyers + 1
            print("There are", tickets, "tickets remaining.")
        elif buy > 4:
            print("You cannot buy that many (4 max).")
        elif tickets - buy < 0:
            print("You can only buy what remains. Please see previous 'remaining' message.")
    
    print()
    print("There was a total of", buyers, "buyers.")
    

    【讨论】:

      【解决方案2】:
      buy = int()
      ticket_num = 15
      buyers = 0
      
      while ticket_num > 0:
          buy = int(input("How many tickets would you like to purchase? "))
          if buy > 4:
              print("You cannot buy that many (4 max).")
              #buy = input("How many tickets would you like to purchase? ")
          else:
              if ticket_num - buy>=0:
                  ticket_num = ticket_num - buy
                  print("There are currently", ticket_num, "remaining.")
                  buyers = buyers + 1
              else:
                  print("There are currently", ticket_num, "remaining. You can buy up to", ticket_num, "tickets")
      print()
      
      print("The total number of buyers was:", buyers)
      

      这里是解决方案。问题是你得到了两次输入。首先在while下面。其次是 if 语句。

      【讨论】:

        猜你喜欢
        • 2021-01-03
        • 2016-03-22
        • 2014-11-08
        • 1970-01-01
        • 1970-01-01
        • 2011-06-19
        • 2011-03-04
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多